var function1 = function(){};
var function2 = function(){};
function1.call(function2.prototype);
我花了太多时间试图理解上面的代码。任何人都可以解释在上述情况下是如何变化的吗function1
?function2
我可以function1
在function2
. 所以,我的结论function
一定是变了。
var function1 = function(){};
var function2 = function(){};
function1.call(function2.prototype);
我花了太多时间试图理解上面的代码。任何人都可以解释在上述情况下是如何变化的吗function1
?function2
我可以function1
在function2
. 所以,我的结论function
一定是变了。
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.
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)