this到底是谁

js中函数的4种调用方式


1.作为普通函数来调用

alert(window.xx);//undefined

function t() {
    this.xx = 333;
}

t();
alert(window.xx);//333


解释:
作为普通函数来调用this时,this的值指向->windwo,准确的说,this为null,

但被解释成window,在ECMASCRIPT5标准中,如果this为null,则解释成undefined




2.作为对象的方法来调用

//对象属性

var obj = {xx:999, yy:888, t:function () {alert(this.xx)}};
obj.t();//999

<pre name="code" class="javascript">var obj = {xx:999, yy:888, t:function() {alert(this.xx)}};
obj.t();//999

var dog = {xx:'wangwang'};
dog.t = obj.t;
dog.t();// wangwang

//函数
show = function() {
    alert('show' + this.xx);
}

dog.t = show;
dog.t();//show wangwang



解释:
this指向方法的调用者,即该对象

 this指向其调用那一刻的调用者,即
母体对象

不管被调用函数,声明时属性方法,还是函数,this都指向母体对象


3.函数作为构造函数调用时
js中没有类的概念,创建对象时用构造函数来完成,或者直接用json格式{}来写对象

new dog发生的事情:
1.系统创建空对象{},(空对象construct属性指向dao函数)
2.把函数的this指向该空对象
3,执行该函数
4.返回该对象

function dog(name, age) {
    this.name = name;
    this.age = age;
    this.bark = function () {
        alert('this is' + this.name );
    }
}

用构造函数创建对象
var dog = new dog('huzi', 2);
dog.bark();//this is huzi


4.函数通过call,apply调用
语法格式:函数.call(对象,参数1,参数2...参数N);

function t(num) {
    alert(this.age);
    alert(this.age + num);
}

var human = {name:'lisi',age:28};
human.t = t;
human.t(-10);//输出28 18 ,this指向了human,但是human多了一个方法

//接下来,不把t赋值为human的属性,也能把this指向human
var wangwu = {name:'wangwu', age:30};
t.call(wangwu,5);//输出 30 35


你可能感兴趣的:(this到底是谁)