this的指向
函数内部
function log() {
//指向全局对象
console.log(this);
}
对象中的方法
var tom = {
name: "tom",
walk: function () {
//指向调用方法的对象
return this.name + " have an apple";
}
};
构造函数
function Cat(name, age) {
//指向新对象
this.name = name;
this.age = age;
this.eat = function () {
return this.name + " eat fish";
}
}
apply
function Point(x, y) {
this.x = x;
this.y = y;
}
var point0 = new Point(1, 1);
Point.prototype.move = function (a, b) {
this.x += a;
this.y += b;
};
var circle0 = {x: 1, y: 1, r: 1};
//指向apply的第一个参数
point0.move.apply(circle0, [8, 8]);