最近研究了 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
来源: http://www.bubuko.com/infodetail-2557972.html