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

    4.作为构造函数

    new FooCoder();

    函数内部的this指向新创建的对象。

    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:

    var name = "clever coder";
    var person = {
        name : "foocoder",
        hello : function(sth){
            var that = this;
            var sayhello = function(sth) {
                console.log(that.name + " says " + sth);
            };
            sayhello(sth);
        }
    }
    person.hello("hello world");//foocoder says hello world

    6.使用call和apply设置this

    person.hello.call(person, "world");

    apply和call类似,只是后面的参数是通过一个数组传入,而不是分开传入。两者的方法定义:

    call( thisArg [,arg1,arg2,… ] );  // 参数列表,arg1,arg2,...
    apply(thisArg [,argArray] );     // 参数数组,argArray

    两者都是将某个函数绑定到某个具体对象上使用,自然此时的this会被显式的设置为第一个参数。

    简单地总结

    简单地总结以上几点,可以发现,其实只有第六点是让人疑惑的。

    其实就可以总结为以下几点:

    1.当函数作为对象的方法调用时,this指向该对象。

    2.当函数作为淡出函数调用时,this指向全局对象(严格模式时,为undefined)

    3.构造函数中的this指向新创建的对象

    4.嵌套函数中的this不会继承上层函数的this,如果需要,可以用一个变量保存上层函数的this。

    再总结的简单点,如果在函数中使用了this,只有在该函数直接被某对象调用时,该this才指向该对象。

  • 相关阅读:
    我的第一个java程序
    ==和equals的区别
    后缀数组题目总结
    后缀数组入门
    【POJ.3415 Common Substrings】后缀数组 长度不小于K的公共子串个数
    【UOJ #519 查查查乐乐】 DP
    【CF-1350 D. Orac and Medians】 思维
    【CF-1350 C
    【CF 1350 B.Orac and Models】 DP
    【POJ-2774】Long Long Message 后缀数组 最长公共子串(出现两次不重叠子串)
  • 原文地址:https://www.cnblogs.com/zjx2011/p/4596578.html
Copyright © 2011-2022 走看看