面試中常常會被問到的,或者作筆試題的時候也會有這樣的問題,因此今天專門對這個問題作個總結;前端
先看個例子:面試
var age = '19' var myObj = { name:'小賴', myAge:this.age, sayName:function(){ console.log(this.name + '今年' + this.age) } } myObj.sayName(); // 小賴今年 undefined var hero = { name:'艾希', age:'100' } myObj.sayName.call(hero); //艾希今年100 myObj.sayName.apply(hero); //艾希今年100 myObj.sayName.bind(hero)(); //艾希今年100
var myObj1 = { name:'小王', myAge:this.age, sayName:function(add, front){ console.log(this.name + '今年' + this.age + '在'+add+'作'+front) } } var heros ={ name:'艾希尼亞', age:'20' } myObj1.sayName.call(heros,'上海','前端'); //艾希尼亞今年20在上海作前端 myObj1.sayName.apply(heros,['上海','前端']); //艾希尼亞今年20在上海作前端 myObj1.sayName.bind(heros,['上海','前端'])(); // 艾希尼亞今年20在上海,前端作undefined ;這裏有錯亂 myObj1.sayName.bind(heros,'上海','前端')(); // 艾希尼亞今年20在上海作前端 myObj1.sayName.bind(heros)('上海','前端'); // 艾希尼亞今年20在上海作前端