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

Difference between this and self in JavaScript

Everyone is aware of this in javascript, but there are also instances of self encountered in the wild, such as here

So, what is the difference between this and self in JavaScript?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Unless set elsewhere, the value of self is window because JavaScript lets you access any property x of window as simply x, instead of window.x. Therefore, self is really window.self, which is different to this.

window.self === window; // true

If you're using a function that is executed in the global scope and is not in strict mode, this defaults to window, and therefore

function foo() {
    console.log(
        window.self === window, // is self window?
        window.self === this,   // is self this?
        this === window         // is this window?
    );
}
foo(); // true true true

If you're using a function in a different context, this will refer to that context, but self will still be window.

// invoke foo with context {}
foo.call({}); // true false false

You can find window.self defined in the W3C 2006 working draft for the Window Object here.


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

...