call()方法
1 call() 可以實現函數調用
2 可以改變函數中this指向 第一個參數是要改變this的值
function fun(a, b) {
console.log(this);
console.log(a, b);
console.log('好好學習!');
}
var obj = {
num: 100
};
fun(); // window.fun() 此時this === window
// 1 call() 可以實現函數調用
fun.call();
// 2 可以改變函數中this指向 第一個參數實現this的改變
fun.call(obj,10,20); //this 指向{num: 100}
示例:
function Fa(name, age) {
console.log(this);
this.name = name;
this.age = age;
}
function Son(name, age) {
// new Son的時候 this指向Son的實例Son{..}
Fa.call(this, name, age); // Fa()
}
var zyc = new Son('張有才', 22);
console.log(zyc.name, zyc.age);