码迷,mamicode.com
首页 > 移动开发 > 详细

javascript中的call.apply方法是针对function本身定义的内容,并不能将

时间:2018-04-11 10:43:40      阅读:200      评论:0      收藏:0      [点我收藏+]

标签: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本身定义的内容,并不能将

标签:www.   new   asc   参考   需要   继承   内容   实现继承   on()   

原文地址:https://www.cnblogs.com/Andres/p/8793542.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!