最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Classes - 'this' vs 'self' - Stack Overflow

programmeradmin1浏览0评论

I'm using the new ES6 Classes and am having a hard time understanding why I can reference the this variable is one of the methods.

//CLASS

class Form{ 
    constructor(){
        var self = this;
    }   

    assemble(){
        log(self);
    }
}

//CALLED

var form = new Form();
form.assemble();

//RETURN

window object (not the reference to the class object)

I'm using the new ES6 Classes and am having a hard time understanding why I can reference the this variable is one of the methods.

//CLASS

class Form{ 
    constructor(){
        var self = this;
    }   

    assemble(){
        log(self);
    }
}

//CALLED

var form = new Form();
form.assemble();

//RETURN

window object (not the reference to the class object)
Share Improve this question asked Nov 28, 2016 at 18:26 user7892649user7892649 3
  • Possible duplicate of using the 'this' variable within object constructor – user47589 Commented Nov 28, 2016 at 18:29
  • Possible duplicate: How does the “this” keyword in Javascript act within an object literal? – Igor Commented Nov 28, 2016 at 18:29
  • 3 self is an actual, existing property on window: developer.mozilla/en-US/docs/Web/API/Window/self You are redefining it in your constructor as a local variable, temporarily, and then doing nothing with it. In your assemble() method, you are NOT actually referencing that self variable you declared in your constructor, you are referencing window.self. – Jeff McCloud Commented Nov 28, 2016 at 18:32
Add a ment  | 

1 Answer 1

Reset to default 3

this isn't a variable. It's more like a hidden argument to functions.

You can't access self in your example because it's a local variable within the constructor, so it's not available to your assemble method.

You don't need self at all for your example, just use this:

class Form {
    assemble(){
        log(this);             // ***
    }
}
var form = new Form();
form.assemble();

If you were passing form.assemble to something that wouldn't guarantee to call it with the right this, you could define assemble as an instance function member instead, by defining it in the constructor; then it would close over self. But you don't need self for this in ES2015 and above; just use an arrow function, which closes over this:

class Form {
    constructor(){
        var self = this;
        this.assemble = () => {
            log(this);
        };
    }   
}
var form = new Form();
form.assemble();          // Works
var f = form.assemble;
f();                      // Also works

But odds are you don't need to do that.

发布评论

评论列表(0)

  1. 暂无评论