Methods指的是object中,包含了function defined的property。
var me = {
name: 'Azer',
age: 18,
introduce: function() {
return "My name is " + this.name + ", I'm " + this.age + " years old.";
}
}
在JavaScript中 所有的function其實都是method,
如果某個function不屬於一個object,
這個function就是屬於global object。
在一般情況下沒辦使用別的object的method,
var me = {
name: 'Gururinbo',
age: 18,
maho: function() {
return "My name is " + this.name + ", I'm " + this.age + " years old.";
}
}
var you = {
name: 'Mumi',
age: 18,
introduce: function() {
return "My name is " + this.name + ", I'm " + this.age + " years old.";
}
}
you.maho(); //you.maho is not a function
系統會告訴你 you.maho is not a function
,
如果使用 call()
就可以調用(invoke)別的object的method了。
me.maho.call(you) //My name is Mumi, I'm 18 years old.
you.introduce.call(me) //My name is Gururinbo, I'm 18 years old.
如果要傳入 argument也是允許的:
var me = {
name: 'Gururinbo',
age: 18,
maho: function(location) {
return "My name is " + this.name + ", I'm " + this.age + " years old. Live in " + location + ".";
}
}
var you = {
name: 'Mumi',
age: 18,
introduce: function() {
return "My name is " + this.name + ", I'm " + this.age + " years old.";
}
}
me.maho.call(you, "Taiwan"); // My name is Mumi, I'm 18 years old. Live in Taiwan.
apply()
和call()
的用法其實很類似,
用剛剛的例子:
console.log(you.introduce.apply(me)); //My name is Gururinbo, I'm 18 years old.
可以得到相同的結果,
而兩者的不同之處在於,apply()
的argument必須要是array。
var me = {
name: 'Gururinbo',
age: 18,
maho: function(location, area) {
return "My name is " + this.name + ", I'm " + this.age + " years old. Live in " + location + " " + area + ".";
}
}
var you = {
name: 'Mumi',
age: 18,
introduce: function() {
return "My name is " + this.name + ", I'm " + this.age + " years old.";
}
}
me.maho.apply(you, "Taiwan", "Taipei");
// CreateListFromArrayLike called on non-object
如果傳的不是array,會丟出錯誤訊息。
將argument改為array,
me.maho.apply(you, ["Taiwan", "Taipei"])
// My name is Mumi, I'm 18 years old. Live in Taiwan Taipei.
var locate = ["Taiwan", "Keelung"]
me.maho.apply(you, locate);
// My name is Mumi, I'm 18 years old. Live in Taiwan Keelung.