Lee*_*iam 4 javascript oop javascript-namespaces
// Define a class like this
function Person(name, gender){
// Add object properties like this
this.name = name;
this.gender = gender;
}
// Add methods like this. All Person objects will be able to invoke this
Person.prototype.speak = function(){
alert("Howdy, my name is" + this.name);
}
// Instantiate new objects with 'new'
var person = new Person("Bob", "M");
// Invoke methods like this
person.speak(); // alerts "Howdy, my name is Bob"
Run Code Online (Sandbox Code Playgroud)
如何定义命名空间?
您只需创建一个包含所有类/函数的新对象:
var myNamespace = {};
myNamespace.Person = function (name, gender) {
// Add object properties like this
this.name = name;
this.gender = gender;
}
myNamespace.Person.prototype.speak = function() {
alert("Howdy, my name is" + this.name);
}
// Instantiate new objects with 'new'
var person = new myNamespace.Person("Bob", "M");
// Invoke methods like this
person.speak(); // alerts "Howdy, my name is Bob"
Run Code Online (Sandbox Code Playgroud)
MDN有一篇解释JavaScript命名空间的文章.