下面的例子创建了带有三个属性的对象(firstName、lastName、fullName)。
var person = {
firstName:"Bill",
lastName: "Gates",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
person.fullName(); // 将返回 "Bill Gates"
fullName 属性是一个方法。person 对象是该方法的拥有者。
fullName 属性属于 person 对象的方法。
call() 方法是预定义的 JavaScript 方法。
它可以调用对象的方法用于其他对象
例如: 调用person的方法用于person1中。
var person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates",
}
var person2 = {
firstName:"Steve",
lastName: "Jobs",
}
person.fullName.call(person1); // 将返回 "Bill Gates"
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");
apply() 方法与 call() 方法非常相似:
在本例中,person 的 fullName 方法被应用到 person1:
var person = { fullName: function() { return this.firstName + " " + this.lastName; } } var person1 = { firstName: "Bill", lastName: "Gates", } person.fullName.apply(person1); // 将返回 "Bill Gates"
不同之处是:
call() 方法分别接受参数。
apply() 方法接受数组形式的参数。
如果要使用数组而不是参数列表,则 apply() 方法非常方便。
apply() 方法接受数组中的参数:
var person = { fullName: function(city, country) { return this.firstName + " " + this.lastName + "," + city + "," + country; } } var person1 = { firstName:"John", lastName: "Doe" } person.fullName.apply(person1, ["Oslo", "Norway"]);