你能解释一下为什么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
这是一个重现错误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); }; }
要么
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); }; }
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); }; }