javascript中的call.apply方法是針對function本身定義的內容,並不能將

來源:互聯網
上載者:User

標籤:www.   new   asc   參考   需要   繼承   內容   實現繼承   on()   

最近研究了js的繼承,看了幻天芒的文章http://www.cnblogs.com/humin/p/4556820.html#3947420,明白了最好是使用apply或call方法來實現繼承。

但是對於call能不能將funciton的prototype內容一同複製,有疑惑,實驗之後發現是不行的。看下面的代碼,c.g()系統是報錯不識別,不認為其是一個函數。

function f(){
this.a ="a";
this.b = function(){
console.log("b");
}
/*
this.g = function(){
console.log("this is g in f().");
}
*/
}
f.prototype.g = function(){
console.log("this is g in prototype.");
}

function e(){
f.call(this);
}
var c = new e();
console.log(c.a); //彈出a
c.b(); //彈出b

var ff = new f();
ff.g();//this is g in prototype.
c.g();//c.g is not a function

 

如果要實現對f的完全繼承,還需要複製其原型鏈中的內容。參考以下代碼:

function f(){
this.a ="a";
this.b = function(){
console.log("b");
}
}
f.prototype.g = function(){
console.log("this is g in prototype.");
}

function e(){
f.call(this);
//f.prototype.call(this);
}

(
function(){
var Super = function(){};
Super.prototype = f.prototype;
e.prototype = new Super();
}
)();
var c = new e();
console.log(c.a); //彈出a
c.b(); //彈出b

var ff = new f();
ff.g();//this is g in prototype
c.g();//this is g in prototype

javascript中的call.apply方法是針對function本身定義的內容,並不能將

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.