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

function1.call(function2.prototype);

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

功能混合

我可以function1function2. 所以,我的结论function一定是变了。

4

2 回答 2

5

Given your code example, the value of this in that invocation of function1 will be set to the value of the function2.prototype object.

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


function1.call(function2.prototype);

So methods (or other values) on function2.prototype will be accessible from this inside function1.

But if they're simply invoked as like this:

this.someMethod();

then the value of this inside the method will be the actual prototype object. This would be an unusual use.


The code example from your link seems to be this:

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

In this example, the asCircle function adds methods to whatever is provided as its this value. So basically, Circle.prototype is being enhanced with additional methods as a result of this invocation.

As you can see, the .area() method becomes available in the prototype chain of Circle after it was assigned via that invocation.

So it's not that the function being invoked is using the methods, but just the opposite... it's providing new methods.

于 2013-02-22T01:03:21.390 回答
2

they aren't. your code is calling function1 using function2's prototype as the context. So in the call, "this" will map to function2's prototype, instead of the window object (assuming you're calling it from a browser)

于 2013-02-22T01:03:11.673 回答