javascript關於call與apply方法詳解

每一個函數都包含兩個非繼承而來的方法:call與apply。這兩個方法的用途都是在特定的作用域中調用函數,也就是動態改變函數體內this對象。換句話說,可以將函數對象繼承到當前上下文(this)中來使用。

官方示例1:

function Product(name, price) {
  this.name = name;
  this.price = price;
}

function Food(name, price) {
  Product.call(this, name, price);
  this.category = 'food';
}

function Toy(name, price) {
  Product.call(this, name, price);
  this.category = 'toy';
}

var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);

官方示例2:

var person = {
    firstName:"John",
    lastName: "Doe",
    fullName: function () {
        return this.firstName + " " + this.lastName;
    }
}
person.fullName();         // Will return "John Doe"

var myObject = {
    firstName:"Mary",
    lastName: "Doe",
}
person.fullName.call(myObject);  // Will return "Mary Doe"

綁定一些函數用於傳遞參數

function sum(x , y){
    return x+y;
}
function call1(num1 , num2){
    return sum.call(this , num1 , num2);
}

function apply1(num1 , num2){
    return sum.apply(this , [num1,num2]);
}

擴充作用域

window.color = 'red';
var obj = {color:'blue'};
var obj2 = {color:'yellow'};
function showColor(){
    alert(this.color);
}
//showColor();  //red
//showColor.call(window); //red
//showColor.call(obj); //blue

可以做到方法與對象的解耦

call方法的簡單模擬與實現

function test1(a , b){
    return a+b;
}

// 自定義的對象(js中大寫的函數名默認爲自定義對象)
function Obj(x, y){
    this.x = x ; 
    this.y = y ;
    return x*y;
}

var o = new Obj(10 , 20);
o.method = test1 ;
alert(o.method(o.x , o.y));
delete o.method;

test1.call(o,o.x ,o.y);   //200
發佈了85 篇原創文章 · 獲贊 12 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章