微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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);
  };
}

原文地址:https://www.jb51.cc/js/149910.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐