zoukankan      html  css  js  c++  java
  • JS中的this都有什么作用?

    1、全局代码中的this  是指向全局对象,在浏览器中是window 

    alert(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:

    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、使用apply和call设置this

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

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

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

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

    总结this:

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

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

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

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

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

    1. obj.foocoder();  
    2. foocoder.call(obj, ...);  
    3. foocoder.apply(obj, …);  

    原文地址:http://www.cnblogs.com/aaronjs/archive/2011/09/02/2164009.html#_h1_6  

    工作并不只是为了那点工资,而是为了创造一份属于自己的事业
  • 相关阅读:
    可重入函数
    进程间通信的方法和实现
    Qt之Qprocess
    mysql学习(十二)内置函数
    mysql学习(十一)嵌套查询 排序 分组
    mysql学习(十)多表查询
    ubuntu 12.04 安装谷歌浏览器
    mysql学习(九)sql语句
    mysql学习(八)数据表类型-字符集
    mysql远程连接问题-http://www.cnblogs.com/jerome-rong/archive/2013/03/05/2944264.html
  • 原文地址:https://www.cnblogs.com/zouer/p/4252847.html
Copyright © 2011-2022 走看看