方法重用
使用 call()
方法,您可以编写能够在不同对象上使用的方法。
函数是对象方法
在 JavaScript 中,函数是对象的方法。
如果一个函数不是 JavaScript 对象的方法,那么它就是全局对象的函数(参见前一章)。
下面的例子创建了带有三个属性的对象(firstName
、lastName
、fullName
)。
//带参数的 call() 方法
//call() 方法可接受参数:
//实例
var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates"
}
person.fullName.call(person1, "Seattle", "USA");