今天我們將講解JavaScript的幾點Function methods,分別是bind, call以及apply method解釋其作用方式
昨天講解了JavaScript Prototype chain(原型鏈),今天將講解三種常用的Function prototype methods
let Jeremy = {
name: 'Jeremy',
age: 27,
};
function getAge(){
return this.age;
}
let newAge = getAge.bind(Jeremy); //透過bind方法將getAge函式綁定到Jeremy物件
console.log(newAge())
let Jeremy = {
name: 'Jeremy',
age: 27,
};
function getAge(height){
console.log(this.name + this.age + "歲 ," + "身高為" + height + "cm");
}
getAge.call(Jeremy, 183); //透過call方法將getAge函式綁定到Jeremy物件並設定height參數
let Jeremy = {
name: 'Jeremy',
age: 27,
};
function getAge(height){
console.log(this.name + this.age + "歲 ," + "身高為" + height + "cm");
}
getAge.call(Jeremy, [183]);//透過apply方法將getAge函式綁定到Jeremy物件並以array形式設定height參數