教程集 www.jiaochengji.com
教程集 >  脚本编程  >  javascript  >  正文 javascript面向对象编程之this详解

javascript面向对象编程之this详解

发布时间:2014-11-14   编辑:jiaochengji.com
本篇文章介绍下javascript中的this用法,这个this是js中的大坑啊,让人迷惹让人愁,它具有晚绑定的特性,相信看了本文,你的这些迷惹就会被稀释了,一切都豁然开朗了。

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:
 

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会被显式的设置为第一个参数。

您可能感兴趣的文章:
javasrcipt 面向对象编程的例子
javascipt面向对象扩展的例子
javascipt面向对象之成员函数实例
javascript面向对象之this用法举例
javascript面向对象编程之this详解
javascript技术难点(三)之this、new、apply和call详解
JavaScript 面向对象(OOP)的语法参考
JavaScript中this关键字用法详解
详解js和jquery里的this关键字
JavaScript中的面向对象(object-oriented)编程

关键词: js this的用法  面向对象   
[关闭]
~ ~