zoukankan      html  css  js  c++  java
  • 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指向节点元素对象

    多看,多思考,多练习,多总结
  • 相关阅读:
    [LuoGu] P1004 方格取数
    [LuoGu] P1018 乘积最大
    [LuoGu] P2758 编辑距离
    [JZOJ] 01知多少
    [LuoGu] P1731 生日蛋糕
    $mathcal{Const,Inline,Register}$用法总结
    T2027 蜈蚣
    T57274 黑暗城堡
    P2312 解方程
    AT2412 最大の和
  • 原文地址:https://www.cnblogs.com/huanqiuxuexiji/p/9076243.html
Copyright © 2011-2022 走看看