作为方法来调用函数
在 JavaScript 中,您可以把函数定义为对象方法。
下面的例子创建了一个对象(myObject),带有两个属性(firstName 和 lastName),以及一个方法(fullName):
实例
var myObject = {
firstName:"Bill",
lastName: "Gates",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
myObject.fullName(); // 将返回 "Bill Gates"
亲自试一试
fullName 方法是一个函数。该函数属于对象。myObject 是函数的拥有者。
被称为 this 的事物,是“拥有”这段 JavaScript 代码的对象。在此例中,this 的值是 myObject。
测试一下!修改这个 fullName 方法来返回 this 的值:
实例
var myObject = {
firstName:"Bill",
lastName: "Gates",
fullName: function () {
return this;
}
}
myObject.fullName(); // 将返回 [object Object](拥有者对象)
亲自试一试
以对象方法来调用函数,会导致 this 的值成为对象本身。