javascript之this详解

javascript的this不同于java、php等的this,javascript的this灵活多变比较复杂,下面就一一介绍不同情况下的this。

1.函数作为普通函数调用时,this指向window,准确的说this为null,但被解释成window。下面看一个例子

console.log(window.xx);//undefined
function t(){
    this.xx  = 'jhon';
}
t();
console.log(window.xx);//jhon 

2.函数作为对象的方法来调用时,this指向方法的调用者,即母体对象,不管被调用函数声明时属于谁。下面看一个例子证明这一点。

var obj = {name:'name',age:2,t:function(){console.log(this.name)}};
var dog = {name:'wangcai'};
dog.t = obj.t;
dog.t();
/*结果打印的是wangcai*/

3.函数作为构造函数调用时,请看下面分析的例子

function Dog(name,age){
    this.name = name;
    this.age = age;
    this.bark = function(){
        console.log("i am " + this.name);    
    }
}

var dog = new Dog('huzi',2);
dog.bark();
/*
结果为:i am huzi
结果分析
new Dog发生了以下几个步骤:
a.系统创建空对象{}(空对象constructor属性指向Dog函数)
b.把函数的this指向空对象
c.执行该函数
d.返回该对象
*/

function Dog(name,age){
    this.name = name;
    this.age = age;
    this.bark = function(){ 
    }
    return 'abc';
}

var dog = new Dog('huzi',2);
console.log(dog);
/*
上面的dog是什么呢?
经过打印可以知道dog仍热是一个对象,而不是'abc'.因此在构造函数中return的值是忽略的,还是返回对象。
*/

4.函数通过call、apply调用其中this也要发生变化。

call函数语法:call([thisObj[,arg1[, arg2[,   [,.argN]]]]]) arg1...argN可以是任意类型。

apply函数语法:apply([thisObj[,argArray]])   第二个参数是一个数组。

call和apply用法和意义一样,下面对call进行解释:

fn.call(对象obj,参数1,参数2...参数n)

运行如下:

a).fn函数中的this指向对象obj

b).运行fn(参数1,参数2...参数n);

具体例子:

function Animal(){
    this.name = 'Animal';
    this.showName = function(){
        console.log(this.name);
    }
}
function Dog(){
    this.name = 'dog';
}
var animal = new Animal();
var dog = new Dog();
animal.showName.call(dog);
/*
结果:dog
*
/

下面看几个例子巩固一下:

xx = "this is window";
var dog = {xx:'dog',showName:function(){console.log(this.xx);}};
var temp = dog.showName;
temp();
/*结果:this is window*/
xx = "this is window";
var dog = {xx:'dog',showName:function(){console.log(this.xx);}};
var cat = {xx:'cat'};
(cat.showName = dog.showName)();
/*结果:this is window */

请思考一个问题:有this操作的,( this.age = XX)的函数不能直接调用而是要new来调用?这个说法是对的,因为直接调用的this指向window,将会污染全局变量。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值