当this
位于普通函数中, this
的值指向window
,准确的说this为null, 但是被解释成window
alert(window.xx);
function t() {
this.xx = 33;
this.yy = null;
}
alert(window.xx);
alert(window.yy); //输出undefined
作为对象的方法来调用, this
指向方法的调用者, 即该对象
var obj = {
xx: 999,
yy: 888,
t: function() {
alert(this.xx);
}
};
obj.t();
this
指向, 不管函数位于哪一个位置, 只要关注函数调用的位置
var dog = {
xx: 'wangwang'
};
//this指向dog
dog.t = obj,t;
dog.t();
var show = function() {
alert('show' + this.xx);
}
dog.t = show;
dog.show();
函数作为构造函数调用时候, 在js中没有类的概念, 创建对象是用构造函数来完成
在js
中没有类的概念, 创建对象是使用构造函数来完成或者直接使用json格式来写对象
new Dog()
发生了以下几个步骤
- 系统创建空对象
{}
, 空对象的constructor
属性指向Dog
函数 - 将函数的
this
指向空对象 - 执行该对象
- 返回该对象
function Dog(name, age) {
this.name = name;
this.age = age;
this.bark = function() {
alert('I am' + this.name);
}
}
var dog = new Dog('huzi', 2);
dog.bark();
函数call
和apply
function t(num) {
alert('我的真实年龄是' + this.age);
alert('但是我一般告诉别人我' + (this.age + num));
}
var wangwu = {name: 'wangwu', age:30};
t.call(wangwu, 5);
函数.call(对象, 参数1, 参数2)
运行如下:
- fn函数中
this
指向对象obj
- 运行fn(参数1, 参数2, 参数3)