有许多模式可以创建和处理对象,这是我经常使用的一种。
JavaScript 原型 OOP
var ConstructFoo = function () { //capitalise constructor names
var x = "my private variable";//remember, JS has FUNCTIONAL scope
this.y = 10; //we can read and write to this outside of this function
}
ConstructFoo.prototype.barMethod = function () {
return this.y * 10;
}
var bash = new ConstructFoo();//new keyword is syntactic sugar for creating a new instance
alert(bash.y);//will alert 10
alert(bash.x);//ERROR, this is undefined
alert(bash.barMethod());//will alert 100
var baz = new ConstructFoo(); //new instance, lets prove it
alert(bash === baz); //will alert false
bash = "";
alert(bash.y);//ERROR, this is undefined
alert(baz.y);//alerts 10
不要与 JavaScript 对象混淆:
var foo = {
funcA: function (params) {
var bar = 2;
//etc
return bar;
},
funcB: function (param) {
var bar = param * 2;
//etc
return bar;
}
};
foo.funcA(7);//returns 2
foo.funcB(2); //returns 4
这是一个静态对象。您不会创建它的新实例。如果您在别处更改 foo.funcA,它将影响使用该函数的所有代码。
推荐阅读:O'Reilly 的 JavaScript 模式