【问题标题】:JavaScript assign function to object propertyJavaScript 将函数分配给对象属性
【发布时间】:2016-01-15 03:15:15
【问题描述】:

我正在查看一个 JavaScript 库的源代码,在类定义中遇到了这样的事情:

var MyClass = function() {
    function doSomething() {
        // function definition
    }

    this.doSomething = function() {
        doSomething();
    };
}

所以,我的问题是:有什么理由有人会这样做,而不是像这样简单地将函数分配给对象方法:

this.doSomething = doSomething;

【问题讨论】:

标签: javascript class oop methods


【解决方案1】:

这完全取决于doSomething 实际在做什么。 this 在函数中的绑定方式有所不同。如果您按照您的示例调用它,它不会将 this 绑定到对象,而如果您调用它并将其直接分配给属性,则 this 将绑定到实例:

var MyClass = function() {
  this.n = "Bob";
  function doSomething() {
    console.log(this.n);
  }

  this.doSomething = function() {
    doSomething();
  };
  this.doSomethingDirect = doSomething;
}

var x = new MyClass();

x.doSomething();        //undefined
x.doSomethingDirect();  //"Bob"

【讨论】:

    猜你喜欢
    • 2011-09-22
    • 2014-01-16
    • 1970-01-01
    • 2023-03-29
    • 2014-04-05
    • 2019-03-20
    • 2017-12-04
    • 2016-02-03
    相关资源
    最近更新 更多