You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
varwsscat=function(name){varself=this;varx='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对象的方法或者变量要用selffunctionfunc3(){console.log(this)//指向window对象//this.func();//报错this.func is not a functionself.func();//不能用this.func(),也不能用func()console.log("wsscat's func3");}}varobj=newwsscat('wsscat');obj.func2()
javascript中每个函数解析时,都会创建两个特殊的变量:this和arguments,这两个变量都能在函数体内访问,所以每个函数都有属于自己的this对象和arguments
当然这个this对象是在执行时基于函数的执行环境绑定的,
下面这个函数执行的时候,第一个this指向的就是window对象,因为它在window环境下执行的,第二个this对象指向的是objThis对象,因为它在objThis对象下执行的
当我们把这个构造函数变成对象的时候,这个this就是指向自己的wsscat对象
这里给出一个私有的self参数,这个可以令对象this对私有方法func3可见,所以当我们在构造函数中出现闭包(私有函数/嵌套函数 下面例子中的function func3())都要注意,此时里面的this是属于window对象的
而上面的代码中func和func2里面既可以用self也可以用this来访问wsscat本身的这个对象,因为此时的this等于wsscat这个对象,这个func是在this(即wsscat对象)下面调用的
The text was updated successfully, but these errors were encountered: