Skip to content

Instantly share code, notes, and snippets.

@lovemyliwu
Last active November 18, 2015 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lovemyliwu/c91b9735be0dfc1a8267 to your computer and use it in GitHub Desktop.
Save lovemyliwu/c91b9735be0dfc1a8267 to your computer and use it in GitHub Desktop.
Basic Scope Closure of Javascript
// define root module
var rm = rm || {};
// define a module under root module
rm.person = function (win, doc) {
// current module
var module = {
// module var
coding: "utf-8",
// module function another name is static function
print: function (name, age) {
console.log('name: ' + name + ' age: '+ age);
},
// module class
Person: function (name, age) {
if (!(this instanceof module.Person)) {
// create a new instance for apply arguments
// note new instance is a subclass of Person but nothing customized
return module.Person.apply(new module._Person(), arguments);
}
// call inhert function from super class
this.print();
// instance var
this.name = name;
this.age = age;
// instance function
this.print = function () {
console.log("I'm in a instance begin.");
// call class function
module.Person.prototype.print.apply(this, arguments);
console.log("I'm in a instance end.");
};
// call instance function
this.print();
// return this pointer to comparability not with new keyword initial
return this;
},
_Person: function () {}
};
// module class var and function
module.Person.prototype = {
name: 'class_name',
age: 'class_age',
print: function () {
module.print(this.name, this.age);
}
};
// define subclass of Person
module._Person.prototype = module.Person.prototype;
return module;
}(window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment