'this' keyword, not clear

2019-01-07 21:42发布

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?

8条回答
叼着烟拽天下
2楼-- · 2019-01-07 22:35

this link make you understand : The this keyword

function doSomething() {
   this.style.color = '#cc0000';
}

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript. An onclick property, though, is owned by the HTML element it belongs to.

查看更多
Rolldiameter
3楼-- · 2019-01-07 22:44

The answer is "it depends", since the meaning of this depends on the context in which it is invoked.

For example in things like callbacks, this no longer refers to the current object, but more typically to the DOM element on which the event occurred:

So this identical-looking function:

Foo.prototype.handleSomeEvent = function(e) {
    return this.name;
}

if used as an event callback would try to resolve the name attribute of the element, and not your object's name.

查看更多
登录 后发表回答