Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

How does 'call' work in javascript?

I have a question on 'call' in javascript.

var humanWithHand = function(){
    this.raiseHand = function(){
        alert("raise hand");
    }
}

var humanWithFoot = function(){
    this.raiseFoot = function(){
        alert("raise foot");
    }
}

var human = function(){

    humanWithHand.call( this );
    humanWithFoot.call( this );

}

var test = new human();

so..when I use 'call' as humanWithHand.call(this), what happens internally?

does humanWithHand variable copies (or points?) its properties and members to human variable's prototype?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yehuda Katz has a good writeup of JavaScript's Function#call method. His writeup should answer your question, and many followup questions besides.

When you call a function directly, using the general syntax:

var foo = function() {
  console.log("foo");
  return this;
};
foo(); // evaluates to `window`

Then this inside the function call is whatever this is outside the function call. By default, in the browser, this outside any function calls is window. So inside the function call as above, this is also by default window.

When you call a function using the method-call syntax:

var bar = {
  foo: function() {
    console.log("foo");
    return this;
  }
};
bar.foo(); // evaluates to `bar`

Then this inside the function call is the object to the left of the rightmost period: in this case, bar.

We can simulate this situation using call.

When you set up a function outside an object and want to call it with this inside the function call set to an object, you can:

var foo = function() {
  console.log("foo");
  return this;
}
var bar = { };
foo.call(bar); // evaluates to `bar`

You can use this technique to pass arguments as well:

var foo = function(arg1, arg2) {
  console.log("foo");
  return arg1 + arg2;
}
var bar = { };
foo.call(bar, "abc", "xyz"); // evaluates to `"abcxyz"`

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...