Js当中严格模式下this的指向
-
全局作用下的this
严格模式下,在全局作用域中,this指向window对象(非严格模式也一样)
"use strict" console.log(this,this === window);
-
普通函数当中
严格模式下,普通函数中的this指向**undefined ** (非严格模式指向window对象)
function Fun02(){ console.log(this) } //严格模式下 function Fun01(){ "use strict" console.log(this) } Fun01() //window对象 Fun02() //undefined
-
对象当中
严格模式下,对象的函数中的this指向调用它的对象的实例 (和非严格模式相同)
"use strict"; var obj = new Object(); obj.text = 'hello world'; obj.fun = function(){ return this; } console.log(obj.fun()); //{text:'hello world',fun:f},即obj对象
-
构造函数当中
严格模式下,构造函数当中的this指向构造函数所创建的对象实例。(和非严格模式一样)
"use strict"; function Fun(){ this.text = 'hello world'; this.fun = function(){ console.log(this); //Fun构造函数 return this.text; } } var fun1 = new Fun(); console.log(fun1.fun()); //hello world
-
事件处理函数当中的this
在严格模式下,事件处理函数中的this指向触发事件的目标对象。(和非严格情况相同)
-
内联事件处理函数当中
//undefined <button onclick="alert((function(){'use strict'; return this})());">