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);

  • 相关阅读:
    python函数
    python数据类型补充,copy知识点及文件的操作
    python数据类型
    python介绍
    Linux基础2-2 基础文件管理命令
    Linux基础2-1 根文件系统分析
    Linux基础1-3 命令使用帮助的获取
    Linux基础1-2 ls、cd、date、clock、cal、echo、printf命令使用简介
    Linux基础1-1
    fastDFS环境搭建
  • 原文地址:https://www.cnblogs.com/si812cn/p/1420435.html
Copyright © 2011-2022 走看看