js中的call()方法與apply()方法

來源:互聯網
上載者:User

標籤:window   其他   參數   style   指定   無法   .sh   沒有   erro   

    摘自:http://blog.csdn.net/chelen_jak/article/details/21021101

在web前端開發過程中,我們經常需要改變this指向,通常我們想到的就是用call方法

一、call方法的定義

關於call的定義都很拗口。在我的理解,a.call(b,arg1,arg2..)就是a對象的方法應用到b對象上。例如如下例子:

function add(a,b){alert(a+b);}function reduce(a,b){alert(a-b);}add.call(reduce,1,3) //將add方法運用到reduce,結果為4
二、call可以改變this指向

如下例:

function b(){alert(this)}b(); //windowb.call(); //windowb.call(“a”,2,3); //a

再看一個複雜的例子:

function Animal(){this.name=”animal”;this.showName=function(){alert(this.name)}}function Cat(){this.name=”cat”;}var animal = new Animal();var cat = new Cat();animal.showName(); //結果為animalanimal.showName.call(cat); //原本cat沒有showName方法,但是通過call方法將animal的showName方法應用到cat上,因此結果為cat
三、實現繼承

如下例子:

function Animal(name){this.name=name;this.showName=function(){alert(this.name)}}function Cat(name){Animal.call(this,name); //將Animal應用到Cat上,因此Cat擁有了Animal的所有屬性和方法}var cat = new Cat(“Black Cat”);cat.showName(); //瀏覽器彈出Black Cat
四、apply用法

apply和call的用法只有一個地方不一樣,除此之外,其他地方基本一模一樣

a.call(b,arg1,arg2…)

apply(b,[arg1,arg2]) //apply只有2個參數,它將call的參數(arg1,arg2…)放在一個數組中作為apply的第二參數

 

其他總結:

call方法: 
文法:call([thisObj[,arg1[, arg2[,   [,.argN]]]]]) 
定義:調用一個對象的一個方法,以另一個對象替換當前對象。 
說明: 
call 方法可以用來代替另一個對象調用一個方法。call 方法可將一個函數的物件內容從初始的上下文改變為由 thisObj 指定的新對象。 
如果沒有提供 thisObj 參數,那麼 Global 對象被用作 thisObj。 

apply方法: 
文法:apply([thisObj[,argArray]]) 
定義:應用某一對象的一個方法,用另一個對象替換當前對象。 
說明: 
如果 argArray 不是一個有效數組或者不是 arguments 對象,那麼將導致一個 TypeError。 
如果沒有提供 argArray 和 thisObj 任何一個參數,那麼 Global 對象將被用作 thisObj, 並且無法被傳遞任何參數。

 

程式碼範例:

function Animal(name) {    this.name = name;    this.showName = function() {        console.log(this.name);    };}function Cat(name) {    Animal.call(this, name);}Cat.prototype = new Animal(); //prototype 屬性使您有能力向對象添加屬性和方法。function Dog(name) {    Animal.apply(this, name);}Dog.prototype = new Animal();var cat = new Cat("Black Cat"); //call必須是objectvar dog = new Dog(["Black Dog"]); //apply必須是arraycat.showName();dog.showName();console.log(cat instanceof Animal);console.log(dog instanceof Animal);

 

js中的call()方法與apply()方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.