【问题标题】:What is the difference in method borrowing using call method and using "=" operator in JavaScript?在 JavaScript 中使用调用方法和使用“=”运算符的方法借用有什么区别?
【发布时间】:2020-04-03 15:58:52
【问题描述】:

考虑以下对象

var person1 = {
   name: 'Sam',
   age: 26,
   job: 'teacher',
   testMethod : function() {
     //do something
   }
};

var person2 = {
   name: 'John',
   age: 30,
   job: 'student'
};

我想从 person1 借用 testMethod 到 person2。

//Using = operator
person2.testMethod = person1.testMethod;
person2.testMethod();

//Using call method
person1.testMethod.call(person2)

这两种借贷方式有什么区别?

【问题讨论】:

  • 如果您的函数不使用 person1 的任何内部值,则没有问题,或者如果您的 person1 和 person2 具有相同的结构,则没有问题。
  • @CodeManiac,如果是=,是否会在内存中创建单独的方法定义副本?
  • 不,它不会只创建一个引用,可以访问person2.testMethod,并且在调用方法中你不会在person2上创建引用
  • 第一个版本给person2增加了一个新属性,不是吗?

标签: javascript methods apply


【解决方案1】:

call 方法不会将testMethod 添加到您的第二个对象person2,它只会更改thistestMethod 主体内的绑定,因此this 指向person1它将指向person2

示例

var person1 = {
  firstName:"John",
  lastName: "Doe",
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}
var person2 = {
  firstName:"Mary",
  lastName: "Doe"
}

person1.fullName(); //this will yield John Doe
person1.fullName.call(person2); //this will yield Mary Doe

person2.fullName = person1.fullName;
person2.fullName(); //this will yield also Mary Doe

来自 MDN:

call() 允许属于一个对象的函数/方法 分配并调用不同的对象。

call() 为函数/方法提供了 this 的新值。和 call(),你可以编写一个方法,然后在另一个中继承它 对象,而不必为新对象重写方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-31
    • 2011-02-12
    • 1970-01-01
    • 2021-12-17
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多