Javascript’这个’

你能解释一下为什么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);
  };
}

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...