简体   繁体   中英

Javascript basic inheritance vs Crockford prototypical inheritance

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();
        }

The below is more generic way

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());

What is difference between the above two ?

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");

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!

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM