标签:
var obj = {}; obj.x = 100; obj.y = function(){ alert( this.x ); }; obj.y(); //弹出 100
var checkThis = function(){ alert( this.x); }; var x = ‘this is a property of window‘; var obj = {}; obj.x = 100; obj.y = function(){ alert( this.x ); }; obj.y(); //弹出 100 checkThis(); //弹出 ‘this is a property of window‘
function changeStyle( type , value ){ this.style[ type ] = value; } var one = document.getElementByIdx( ‘one‘ ); changeStyle.call( one , ‘fontSize‘ , ‘100px‘ ); changeStyle(‘fontSize‘ , ‘300px‘); //出现错误,因为此时changeStyle中this引用的是window对象,而window并无style属性。
function changeStyle( type , value ){ this.style[ type ] = value; } var one = document.getElementByIdx( ‘one‘ ); changeStyle.apply( one , [‘fontSize‘ , ‘100px‘ ]); changeStyle(‘fontSize‘ , ‘300px‘); //出现错误,原因同示例三
var obj = { x : 100, y : function(){ setTimeout( function(){ alert(this.x); } //这里的this指向的是window对象,并不是我们期待的obj,所以会弹出undefined , 2000); } }; obj.y();
var obj = { x : 100, y : function(){ var that = this; setTimeout( function(){ alert(that.x); } , 2000); } }; obj.y(); //弹出100
var one = document.getElementByIdx( ‘one‘ ); one.onclick = function(){ alert( this.innerHTML ); //this指向的是one元素,这点十分简单.. };
function test() { this.x = 1; alert(x); } test();
var x = 1; function test() { alert(this.x); } test();//1 var x = 1; function test() { this.x = 0; } test(); alert(x);//0
function test() { alert(this.x); } var o = {}; o.x = 1; o.m = test; o.m(); //1
function test() { this.x = 1; } var o = new test(); alert(o.x);//1
var x = 0; function test() { alert(this.x); } var o = {}; o.x = 1; o.m = test; o.m.apply(); //0 o.m.apply(o);//1
标签:
原文地址:http://www.cnblogs.com/lswit/p/4809368.html