You Don't Know JS建议的继承模式

相对于传统的“class”型的继承:

function Foo(who) {
    this.me = who;
}
Foo.prototype.identify = function() {
    return "I am " + this.me;
};

function Bar(who) {
    Foo.call( this, who );
}
Bar.prototype = Object.create( Foo.prototype );

Bar.prototype.speak = function() {
    alert( "Hello, " + this.identify() + "." );
};

var b1 = new Bar( "b1" );
var b2 = new Bar( "b2" );

b1.speak();
b2.speak();
You Don't Know JS建议的继承模式_第1张图片
1.png

you don't know js建议的是object链接到object的模式: (objects-linked-to-other-objects)OOLO:

var Foo = {
    init: function(who) {
        this.me = who;
    },
    identify: function() {
        return "I am " + this.me;
    }
};

var Bar = Object.create( Foo );

Bar.speak = function() {
    alert( "Hello, " + this.identify() + "." );
};

var b1 = Object.create( Bar );
![Uploading 2_629135.png . . .]
b1.init( "b1" );
var b2 = Object.create( Bar );
b2.init( "b2" );

b1.speak();
b2.speak();

这种方式实现的是和第一种相同的功能,然而却更加简单。

You Don't Know JS建议的继承模式_第2张图片
2.png

你可能感兴趣的:(You Don't Know JS建议的继承模式)