JS中的this到底是谁? JS非常灵活 PHP中指的是当前对象
JS中函数的四种调用方式
1.作为普通的函数来调用时
this的值 指向window,准确地说 this为NULL 但被解释成window。在ES 5标准中,如果this为null 则解释成undefined
alert(window.xx); //undefined
function t(){
this.xx=333;
}
t();
alert(window.xx); //333
2 对象的方法来调用 this指向方法的调用者,即母体对象
不管被调函数 声明是属于方法还是函数
var obj={xx:999,yyy:888} ;
obj.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
3.函数作为构造函数调用时
JS中没有类的概念,创建对象是用构造函数来完成,或者直接用json格式{}来写对象
function Dog(name,age) {
this.name=name;
this.age=age;
this.bark=function (){
alert('I am '+this.name +'!'); //注意此处的this不一定指向dog 取决于被调用外层的this
}
}
var dog=new Dog('huzi',2);
dog.bark(); // i am huzi!
function Pig(){
this.age=99;
return 'abc';
}
var pig=new Pig(); //此处得到的是Pig对象 因为函数作为构造函数运行时,return的值是忽略的 依然返回对象
console.log(pig);
new Dog()发生了以下几个步骤
a.系统创建了空对象{}--------空对象constructor属性指向Dog函数
b.把函数的this指向该空对象
c.执行该函数
d.返回该对象
4.函数通过call apply调用
语法格式: 函数.call(对象,参数1,参数2,参数3....参数n)
function t(num) {
alert('我的真实年龄是 '+this.age+' 岁');
alert('但我一般告诉别人我 '+(this.age+num)+' 岁');
}
var human={name:'lisi',age:28};
human.t=t;
human.t(-10); //this指向了human 但是human多了一个方法
//接下来我们不把t赋为human的属性,也能把this指向human的
var wangwu={name:'wangwu',age:30};
t.call(wangwu,5);
解释:
fn.call(对象,参数1,参数2.....参数n);
运行如下:
a. fn中的this 指向对象obj
b. 运行fn(参数1,参数2.....参数n);
name='this is window';
var obj={name:'php'};
obj.t=function (){
alert(this.name)
}
obj.t(); //php
var dog={name:'huzi'};
dog.t=obj.t; // 当该句完成之后,整个页面也仍然只有一个函数。 相当于引用赋值
dog.t(); //huzi
// ---------------------------------------
var tmp=dog.t; //tmp是一个函数
tmp(); // this is window 相当于window.tmp
// ---------------------------------------
console.log(typeof (dog.t=obj.t)); //表达式必有返回值 而该表达式(dog.t=obj.t)返回的是一个函数 是一个值 即不是通过引用来调用的 而是立即使用函数本身
//效果等同于 function (){alert(this.name)}() 此时this指向null null又会被解释成window
(dog.t=obj.t)(); //this is window
/*
有经验的前段但对JS理解的不深的同学说:
有this操作的函数 this.age=xx 的函数不能直接调用 而是要new来调用
答:这句话没问题,因为如果直接调用this 指向window 将会污染全局变量 这才是最终原因
*/
dog.t.call(obj); //php