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
280 views
in Technique[技术] by (71.8m points)

javascript - 'this' keyword, not clear

I get confused about 'this' keyword in the following codes, there are two 'this':

var Foo = function(string){
  this.name=string // 1st-this
}

Foo.prototype.get_name = function(){
  return this.name // 2nd-this
}

var myFoo = new Foo('John')

the_name=myFoo.get_name()

'the_name' is equal to 'John', the prototype method get the name by return this.name. But can anyone explain to me the 1st-this and 2nd-this, what do they stand for?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In Javascript, the value of this is dependent on the way you call the function.

There are 5 ways to call a function in JS, and they all have effect on this:

  1. new Foo(); <= here, you’re creating a new object, and this will reflect that new object
  2. Foo(); <= here, you're calling the function as-is, and this will be the global object(!)
  3. var obj = { foo: Foo };
    obj.foo();
    <= here, you're calling the function as a method of obj; this will be obj
  4. Foo.call(thisObject, arg1, arg2); <= here, you can specify the value of this in the first argument
  5. Foo.apply(thisObject, [args]); <= here, you can specify the value of this in the first argument

In 4 and 5, the difference between call and apply is that with call, you need to pass all the arguments separately, whereas with apply, you can pass an array containing all the arguments.

Note that in my example 2 above, the function should have been called foo instead of Foo. Since it’s impossible to know off-hand whether a function is supposed to be called with new or not, the consensus is to start the function name with a capital letter if it’s a constructor (and should be used with new); otherwise, it should start with lowercase.


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

...