Javascript基本继承vs Crockford原型继承 [英] Javascript basic inheritance vs Crockford prototypical inheritance

查看:85
本文介绍了Javascript基本继承vs Crockford原型继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Crockford推荐的继承感到困惑,Crockford方法和通用(默认)方式之间的主要区别是什么。

I have a confusion with Crockford recommended inheritance, what is the major difference between the Crockford method and the generic (default) way.

//Crockford method
      function object(o) {
            function F() {}
            F.prototype = o;
            return new F();
        }

以下是更通用的方式

function Base(name) {
    this.name = name;
}

Base.prototype.getName = function () {
    return 'Base :' + this.name;
}

function Child(name) {
    this.name = name;
}

Child.prototype.getName = function () {
    return 'Child :' + this.name;
}

function Kid(name) {
    this.name = name;
}

Kid.prototype.getName = function () {
    return 'Kid :' + this.name;
}

Child.prototype = new Base ("childBase");
Kid.prototype = new Child ("kidChild");

var base = new Base ("myBase");
var child = new Child("myChild");
var kid = new Kid("myKid");

console.log(base.getName());
console.log(child.getName());
console.log(kid.getName());

以上两者有什么区别?

实际上我无法完全理解Crockford方法。任何人都可以帮我弄清楚Crockford方法中通用方法和优点的缺点。

Actually I am not able to completely understand Crockford method. Could any one help me to figure out the drawbacks in the generic way and advantages in Crockford method.

推荐答案

Child.prototype = new Base ("childBase");
Kid.prototype = new Child ("K1", "K2");

使用这些行实例化两个对象,这些对象甚至拥有自己的名称。这有什么用?在更复杂的环境中,这可能会破坏应用程序 - 当 Base 构造函数使用私有变量和特权方法时,它的所有子节点将在同一个实例中共享相同的变量!

with these lines you instantiate two objects, which have even own names. What is that good for? In more complicated environments this potentially even breaks the application - when the Base constructor uses private variables and privileged methods, all its children will share the same variables in the same instance!

因此,人们通常不应该使用这种方式,而是使用Crockfords函数,旧版本的 Object.create 。它将使用 Base.prototype 调用,创建一个直接从这个继承的新对象 - 它只设置原型链,但不执行任何构造函数代码。 了解Crockford的Object.create垫片将帮助您了解详细信息。然后,创建的对象非常适合成为Children的原型对象。另请阅读此答案

Therefore, one generally should not use this way but Crockfords function, the older version of Object.create. It will, called with Base.prototype, create a new object that inherits directly from this one - it only sets up the prototype chain, but does not execute any constructor code. Understanding Crockford's Object.create shim will help you with the details. The created object then is perfect to be the prototype object of the Children. Read also this answer.

这篇关于Javascript基本继承vs Crockford原型继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆