javascript之this

总结一句话:javascript函数里的this,始终指向调用该函数的直接对象。当然通过apply(),call(),bind()这几个方法可以更改this除外

实例1:alert(this === window);  //true            调用该函数的直接对象是全局window

实例2:var test = function() { alert(this === window)}; test(); //true          调用该函数的直接对象仍是全局window

实例3:var test = function() { alert(this === window)}; new test(); //false       因为new关键字创建了一个空对象,相当于由这个空对象作为构造函数调用的直接对象,此时this就不是指向window而是指向空对象,并将空对象进行初始化作为返回值。

实例4:var test = { 'a': 1, 'b': function(){ alert(this === test);}}; test.b() //true     这是test作为函数test.b调用的直接对象

实例5: var test = {'a': 1, 'b': {'b1': function(){ alert(this === test.b); }}}; test.b.b1();  //true   这时test.b作为函数test.b.b1调用的直接对象 

实例6: var test = function(){ var inner = function(){ alert(this === window);} inner(); }; test();  //true   类似闭包函数里的this,无论多少层,调用函数的直接对象始终为全局window

实例7: 关于原型链继承   var test = function(){};  var test2 = function(){ this.a = function(){ alert(this === p1);}}; var p2 = new test2(); test.prototype = p2; test.prototype.constructor = test;var p1 = new test(); p1.a(); //true      此时p1作为函数p2.a调用的直接对象

实例8:dom节点事件监听函数的this  <div onclick="shw(this)"></div>   此时的this指向节点元素对象

猜你喜欢

转载自www.cnblogs.com/huanqiuxuexiji/p/9076243.html