zoukankan      html  css  js  c++  java
  • 详解JavaScript中的this

    JavaScript中的this总是让人迷惑,应该是js众所周知的坑之一。 个人也觉得js中的this不是一个好的设计,由于this晚绑定的特性,它可以是全局对象,当前对象,或者…有人甚至因为坑大而不用this。

    其实如果完全掌握了this的工作原理,自然就不会走进这些坑。来看下以下这些情况中的this分别会指向什么:

    1.全局代码中的this

     alert(this);  //window

    全局范围内的this将会指向全局对象,在浏览器中即使window。

    2.作为单纯的函数调用

    function fooCoder(x) {

    this.x = x;
    }
    fooCoder(2);
    alert(x);// 全局变量x值为2
    这里this指向了全局对象,即window。在严格模式中,则是undefined。
    3.作为对象的方法调用
     
    var name = "clever coder";
    var person = {
    name : "foocoder",
    hello : function(sth){
    console.log(this.name + " says " + sth);
    }
    }
    person.hello("hello world");
    输出 foocoder says hello world。this指向person对象,即当前对象。
    4.作为构造函数
     
    new FooCoder();
    函数内部的this指向新创建的对象。
    5.内部函数
     
    var name = "clever coder";
    var person = {
    name : "foocoder",
    hello : function(sth){
    var sayhello = function(sth) {
    console.log(this.name + " says " + sth);
    };
    sayhello(sth);
    }
    }
    person.hello("hello world");//clever coder says hello world

    在内部函数中,this没有按预想的绑定到外层函数对象上,而是绑定到了全局对象。这里普遍被认为是JavaScript语言的设计错误,因为没有人想让内部函数中的this指向全局对象。一般的处理方式是将this作为变量保存下来,一般约定为that或者self:

  • 相关阅读:
    (引)spring学习笔记1.什么是控制反转
    Arduino 各种模块篇 步进电机 step motor 舵机 servo 直流电机 总复习
    Raspberry Pi Wireless Adaptor
    Pyramid 使用总结1
    Arduino 各种模块篇 人体红外感应模块 proximity sensor
    Pyramid 使用总结2
    Webcam Streaming Desktop Recording on Linux for ubuntu or its destros
    Arduino 各种模块篇 步进电机 step motor( 不用库,不用shield, 纯)
    Arduino 各种模块篇 motor shield 电机扩展板(舵机、直流电机、步进电机party)
    转载 stepper motors
  • 原文地址:https://www.cnblogs.com/chayan/p/5805067.html
Copyright © 2011-2022 走看看