你能解释一下为什么第二次调用fn会出错吗?代码如下.
function Test(n) {
this.test = n;
var bob = function (n) {
this.test = n;
};
this.fn = function (n) {
bob(n);
console.log(this.test);
};
}
var test = new Test(5);
test.fn(1); // returns 5
test.fn(2); // returns TypeError: 'undefined' is not a function
Run Code Online (Sandbox Code Playgroud)
这是一个重现错误http://jsfiddle.net/KjkQ2/的JSfiddle
您的bob函数是从全局范围调用的.因此,this.test指向一个名为test覆盖您创建的变量的全局变量.如果你跑console.log(window.test),你会发生什么.
为了使代码按预期运行,您需要以下其中一项
function Test(n) {
this.test = n;
// If a function needs 'this' it should be attached to 'this'
this.bob = function (n) {
this.test = n;
};
this.fn = function (n) {
// and called with this.functionName
this.bob(n);
console.log(this.test);
};
}
Run Code Online (Sandbox Code Playgroud)
要么
function Test(n) {
this.test = n;
var bob = function (n) {
this.test = n;
};
this.fn = function (n) {
// Make sure you call bob with the right 'this'
bob.call(this, n);
console.log(this.test);
};
}
Run Code Online (Sandbox Code Playgroud)
OR基于闭包的对象
// Just use closures instead of relying on this
function Test(n) {
var test = n;
var bob = function (n) {
test = n;
};
this.fn = function (n) {
bob(n);
console.log(test);
};
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
284 次 |
| 最近记录: |