Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Javascript中的var self = this #52

Closed
Wscats opened this issue Aug 14, 2016 · 2 comments
Closed

Javascript中的var self = this #52

Wscats opened this issue Aug 14, 2016 · 2 comments
Labels

Comments

@Wscats
Copy link
Owner

Wscats commented Aug 14, 2016

javascript中每个函数解析时,都会创建两个特殊的变量:thisarguments,这两个变量都能在函数体内访问,所以每个函数都有属于自己的this对象和arguments

当然这个this对象是在执行时基于函数的执行环境绑定的,

  • 即在全局对象中,this指向的是window对象;
  • 在自定义函数中,this对象指向的是调用这个函数的对象;

下面这个函数执行的时候,第一个this指向的就是window对象,因为它在window环境下执行的,第二个this对象指向的是objThis对象,因为它在objThis对象下执行的

var wsscat = function(name){
    var self = this;
    this.name = name;
    console.log(this);
    console.log(self);
}
wsscat('wsscat');
window.wsscat('wsscat');//因为它在window对象下执行的
var objThis = {
    x:'autumns',
    wsscat:wsscat
}
objThis.wsscat();//因为它在objThis对象下执行的

当我们把这个构造函数变成对象的时候,这个this就是指向自己的wsscat对象

var wsscat = function(name){
    var self = this;
    this.name = name;
    console.log(this);
    console.log(self);
}
////通过构造函数new一个新对象时,this就指这个新对象
var obj = new wsscat('wsscat');//log wsscat{name:'wsscat'}对象

这里给出一个私有的self参数,这个可以令对象this对私有方法func3可见,所以当我们在构造函数中出现闭包(私有函数/嵌套函数 下面例子中的function func3())都要注意,此时里面的this是属于window对象的

var wsscat = function(name){
    var self = this;
                var x = 'autumns';
    this.name = name;
    console.log(this);
    console.log(self);
    this.func = function(){
        console.log("wsscat's func");
    };
    this.func2 = function(){
        func3();//不能用self.func3()和this.func3()
    }
    //闭包里面,既嵌套函数里面如果想使用wsscat对象的方法或者变量要用self
    function func3(){
        console.log(this)//指向window对象
        //this.func();//报错this.func is not a function
        self.func();//不能用this.func(),也不能用func()
        console.log("wsscat's func3");
    }
}

var obj = new wsscat('wsscat');
obj.func2()

而上面的代码中func和func2里面既可以用self也可以用this来访问wsscat本身的这个对象,因为此时的this等于wsscat这个对象,这个func是在this(即wsscat对象)下面调用的

this.func = function(){
    console.log("wsscat's func");
};
@Wscats Wscats added the notes label Aug 14, 2016
@anjiecc
Copy link

anjiecc commented Jan 14, 2017

写的很好

@zhoushaokun
Copy link

定义了var self = this, self 就相当于一个对象变量,访问self就会按照作用域链的方式进行查找,而这对于this是 行不通的。

@Wscats Wscats closed this as completed Aug 22, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants