10,方法
方法:在一个对象中的函数就是方法
//定义一个对象的方法
var circle = {
radius:10,
area:function () {
return this.radius*this.radius;
}
}
10.1,this
-
在一个方法内部,
this
是一个特殊变量,它始终指向当前对象,也就是circle这个变量。 -
在javascript 调用this,永远指向的是当前的对象,如果是外层的函数,调用this,则默认指向window;(在strict模式下让函数的
this
指向undefined
) -
在方法内部在嵌套一个函数时,this不在指向当前对象,而是会指向unindetify(解决方法:定义一个that,去捕获this!!)
'use strict';
//定义一个对象的方法
var circle = {
radius:10,
area:function () {
return this.radius*this.radius;
}
}
//**在方法内部在嵌套一个函数时,this不在指向当前对象
var xiaoming = {
name: '小明',
birth: 1990,
age: function () {
function getAgeFromBirth() {
var y = new Date().getFullYear();
return y - this.birth;
}
return getAgeFromBirth();
}
};
xiaoming.age(); // Uncaught TypeError: Cannot read property 'birth' of undefined
//解决方法:定义一个that,去捕获this!!
var xiaoming = {
name: '小明',
birth: 1990,
age: function () {
var that = this; // 在方法内部一开始就捕获this
function getAgeFromBirth() {
var y = new Date().getFullYear();
return y - that.birth; // 用that而不是this
}
return getAgeFromBirth();
}
};
xiaoming.age(); // 25
10.2,apply call
解决this的指向问题:指定独立函数的指向对象,参数使用数组形式(apply) 参数按顺序传入(call)
'use strict';
//定义一个对象的方法
var circle = {
radius:10,
area:function () {
return this.radius*this.radius;
}
}
function f1() {
console.log(this.radius*this.radius);
}
f1();//Cannot read property 'radius' of undefined
f1.apply(circle,[]);//100
f1.call(circle)//此处无参数
apply的应用:动态改变函数的行为
'use strict';
var count = 0;
var oldParseInt = parseInt; // 保存原函数
window.parseInt = function () {
count += 1;
return oldParseInt.apply(null, arguments); // 调用原函数
};