可以在这个JSFiddle上看到一个例子
我正在创建一个实例,更改该实例的一个函数,然后在该实例的另一个函数中调用该函数。我在访问更新后的函数中的局部变量和实例变量时遇到了困难。
代码
var MyObj = function (name) {
var that = this;
MyObj.myObjs = (MyObj.myObjs || []),
this.objName = name,
this.objIdx = MyObj.myObjs.length;
MyObj.myObjs.push(this.objName);
this.doOnSetName = function () {};
this.setName = function (name) {
that.doOnNameSet();
that.objName = name;
MyObj.myObjs[that.objIdx] = name;
}
}
var obj1 = new MyObj("obj1");
//obj1.doOnNameSet = function() { alert("objName: "+this.objName) };
//obj1.setName("obj1");
var obj2 = new MyObj("obj2");
obj2.doOnNameSet = function () {
$("#console").append("Old objName: " + this.name
+ "<br />New objName: " + name + "<br />")
};
obj2.setName("obj2 - changed");
$("#console ").append("Objects: <br />*" + MyObj.myObjs.join(", <br />*"));
实际结果
Old objName: undefined
New objName: result
Objects:
*obj1,
*obj2 - changed
期望的结果
Old objName: obj2
New objName: obj2 - changed
Objects:
*obj1,
*obj2 - changed