zoukankan      html  css  js  c++  java
  • javascript this的用法

    this
    在JavaScript中,this通常指向的是我们正在执行的函数本身,或者是指向该函数所属的对象(运行时)。当我们在页面中定义了函数 doSomething()的时候,它的owner是页面,或者是JavaScript中的window对象(或 global对象)。对于一个onclick属性,它为它所属的HTML元素所拥有,this应该指向该HTML元素。
    2.1在几种常见场景中this的变化
    函数示例
    function doSomething ()
    {
    alert(this.navigator); //appCodeName
    this.value = "I am from the Object constructor";
    this.style.backgroundColor = "# 000000";
    }
    1. (A)作为普通函数直接调用时,this指向window对象.
    2. (B)作为控件事件触发时
    1) inline event registration 内联事件注册 .将事件直接写在HTML代码中(<element
    onclick=”doSomething()”>), 此时this指向 window对象 。
    2) Traditional event registration 传统事件注册 (DHTML方式).
    形如 element.onclick = doSomething; 此时this指向 element对象
    3) <element onclick=”doSomething(this)”>作为参数传递可以指向element
    3. (C)作为对象使用时this指向当前对象。形如:new doSomething();
    4. (D)使用apply 或者call方法时,this指向所传递的对象。
    形如:var obj={}; doSomething.apply(obj,new Array(”nothing”); //thisàobj

    追加:如果希望事件调用时仍然把this指定为特定的对象,可以通过以下方法实现:

    Function.prototype.bind = function(obj)
    {
        var method = this;

        var temp = function()
        {
            return method.apply(obj, arguments);
        };

        return temp;
     }

    function load()

    {

         this.aa = "hello";

         this.show = function()

         {

            alert(this.aa);  

         };

    }

    var newclass = new load();

    document.body.onload = newclass.show.bind(newclass);

  • 相关阅读:
    NOIP201208同余方程
    NOIP模拟赛 最佳组合
    NOIP模拟赛 拓展
    CF1253E Antenna Coverage(DP)
    LOJ6033「雅礼集训 2017 Day2」棋盘游戏 (博弈论,二分图,匈牙利算法)
    CF582E Boolean Function(DP,状态压缩,FMT)
    CF750G New Year and Binary Tree Paths(DP)
    Codeforces Round 596 题解
    AGC008E Next or Nextnext(组合计数,神奇思路)
    ARC082E ConvexScore(神奇思路)
  • 原文地址:https://www.cnblogs.com/si812cn/p/1420435.html
Copyright © 2011-2022 走看看