javascript - 这个 JavaScript Function.call 方法在做什么?

标签 javascript function prototype

var function1 = function(){};
var function2 = function(){};

function1.call(function2.prototype);

我花了太多时间试图理解上面的代码。任何人都可以解释一下在上述情况下 function1function2 是如何改变的吗?

functional mixins

我能够在 function2 的对象上调用 function1 中的方法。所以,我的结论是function一定已经改变了。

最佳答案

根据您的代码示例,function1 调用中 this 的值将设置为 function2.prototype 对象的值.

var function1 = function(){
    console.log(this === function2.prototype); // true
};
var function2 = function(){};


function1.call(function2.prototype);

因此,function2.prototype 上的方法(或其他值) 可以从 function1 内的 this 访问。

但是如果它们只是像这样调用:

this.someMethod();

那么方法内的this的值将是实际的原型(prototype)对象。这将是一个不寻常的用途。

<小时/>

您链接中的代码示例似乎是这样的:

var asCircle = function() {
  this.area = function() {
    return Math.PI * this.radius * this.radius;
  };
  this.grow = function() {
    this.radius++;
  };
  this.shrink = function() {
    this.radius--;
  };
  return this;
};

var Circle = function(radius) {
    this.radius = radius;
};
asCircle.call(Circle.prototype);

var circle1 = new Circle(5);
circle1.area(); //78.54
<小时/>

在此示例中,asCircle 函数向作为其 this 值提供的任何内容添加方法。因此,基本上,由于此调用,Circle.prototype 通过其他方法得到了增强。

如您所见,.area() 方法在通过该调用分配后,在 Circle 的原型(prototype)链中变得可用。

所以并不是说被调用的函数正在使用这些方法,而是恰恰相反......它提供了新的方法。

关于javascript - 这个 JavaScript Function.call 方法在做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15015108/

相关文章:

javascript - ReactJS + Material-UI : How to use Material-UI’s FlatButton and Dialog in each TableRow?

excel - 如何在 Countifs 函数的 criteria_range 中做一些数学运算(在 Countif 中使用 OR)

javascript - 帮助查找包含模运算符的 if 语句中的模式

Javascript原型(prototype)函数失败

javascript - 未捕获的类型错误 : Immutable prototype object '#<Object>' cannot have their prototype set

javascript - 单选组显示所选值的项目 jQuery

javascript - 您可以在自定义页面代码上调用或使用数据元素吗?就像 GTM 中的变量

javascript - 如何在图像中动态添加 anchor

c++ - 从模板参数中获取函数参数

javascript - Library.add 不是函数错误