JavaScript作为方法来调用函数
在 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:"John",
lastName: "Doe",
fullName: function () {
return this;
}
}
myObject.fullName(); // 将返回 [object Object](拥有者对象)
以对象方法来调用函数,会导致 this 的值成为对象本身。
通过函数构造器来调用函数
如果函数调用的前面是 new 关键字,那么这是一个构造函数调用。
它看起来像你创建一个新的函数,但由于 JavaScript 函数是对象,你实际上创建一个新对象:
如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h64476.shtml