需要有可以实例化的类,保存私有和公共变量/方法。
只是想检查一下我在原型上的实现是否正确。
之前:(jsFiddle:http: //jsfiddle.net/7UqSv/1/)
var MyObject = (function ()
{
var oid = "'oid123'";
var x = 1;
var y = 1;
incrementx = function()
{
x = x +1;
console.log('value of x: ' + x);
}
incrementxagain = function()
{
x = x +1;
console.log('value of x: ' + x);
}
return {
oid : oid,
incrementx: function (){ incrementx(); },
incrementxagain: function (){ incrementxagain(); }
}
});
var NewMyObject = new MyObject();
NewMyObject.incrementx(); //outputs "value of x: 2"
NewMyObject.incrementxagain(); //outputs "value of x: 3"
console.log('oid ' + NewMyObject.oid); //outputs "oid 'oid123'"
之后:(jsFiddle:http: //jsfiddle.net/7UqSv/6/)
var MyObject = (function ()
{
var oid = "'oid123'";
this.x = 1;
var y = 1;
//*** ADDED REFERENCE TO THIS USING $this
var $this = this;
//*** MOVED 'incrementx' FUNCTION TO PROTOTYPE BELOW
incrementxagain = function()
{
$this.x = $this.x +1;
console.log('value of x: ' + $this.x);
}
return {
oid : oid,
incrementx: function (){ $this.incrementx(); },
incrementxagain: function (){ incrementxagain(); }
}
});
//****** ADDED PROTOTYPE METHOD
MyObject.prototype.incrementx = function() {
this.x = this.x + 1;
console.log('value of x:' + this.x);
}
var NewMyObject = new MyObject();
NewMyObject.incrementx(); //outputs "value of x: 2"
NewMyObject.incrementxagain(); //outputs "value of x: 3"
console.log('oid ' + NewMyObject.oid); //outputs "oid 'oid123'"
两者都有效,但发现我必须在变量上从使用 var 更改为 this 然后在创建对象时在 $this 中存储对 this 的引用,这很奇怪?另外,这意味着由于我的代码有很多变量,我将不得不编写更多代码,因为现在需要对“this”的额外引用?IE:
这个:
结果 = (x + y + z) * ( x + y + z);
变成:
this.result = (this.x + this.y + this.z) * (this.x + this.y + this.z);
只是一个健全的检查,我在这里做的不是 anit 模式或什么?
谢谢