2

JavaScriptを使って単純な古典的な継承を作りたいです。サブクラス化とメソッドのオーバーライドが必要なだけで、prototype.jsや他のライブラリによって提供されるような冗長な構文やベルやホイッスルは必要ありません。

さて、Shelby S. Mooreという名前のこの仲間は、私が望むように機能するソリューションを考え出しました:http: //www.coolpage.com/developer/javascript/Correct%20OOP%20for%20Javascript.html

唯一の問題は、彼がネイティブタイプのオブジェクトと関数を拡張していることです。これにより、私が使用しているライブラリの一部が壊れます。また、一般的な観察として、ネイティブオブジェクトのプロトタイプをいじりたくありません。

シェルビーS.ムーアの例をここに公開しました:http: //jsfiddle.net/christian1974/CEKL5/

例からわかるように、期待どおりに機能します。さて、64.000ドルの質問は次のとおりです。Object.prototypeとFunction.prototypeをいじらずに機能させる方法をお勧めしますか?

私は次のような本当に単純な構文を探していました:

Extend(parent, this);

アイデア全体を捨てて、これを行う既存のライブラリを使用する必要がありますか?私は自分の人生を難しくしすぎていませんか?

4

2 に答える 2

1
function extend(Child, Parent) {
    var F = function() { };
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
    Child.superclass = Parent.prototype;
}

使用法:

function Parent() {}

Parent.prototype.hello = function(name) {
    alert('hello ' + name);
}

function Child() {
    Child.superclass.hello.call(this, 'world');
}

extend(Child, Parent);
于 2012-08-08T07:14:18.417 に答える
1

オブジェクトのプロトタイプを拡張する代わりに、関数を作成してみませinheritsんか?

function inherits(parent)
{
    //just make sure this doesn't get called on the global object (like a regular function)
    //and the parent is an actual constructor reference
    if (this === window || typeof parent !== 'function')
    {
        throw new Error('inherit not possible on window/without constructor');
    }
    //to set the constructor dynamically and secure the constructor of child object
    //I'd say this should do the trick (be weary though, not tested)
    var constr, Proto;
    constr = this.constructor;
    Proto = typeof parent === 'function' ? new parent : parent;//get instance
    this.prototype = Proto.prototype;
    this.constructor = constr;//restore constructor when needed
    if( arguments.length > 1 )
    {
        return parent.apply( this, Array.prototype.slice.call( arguments, 1 ) );
    }
    return parent.call( this );
}

function Foo(someArg)
{
    inherits.apply(this,[Bar,someArg]);
}

そうは言っても、このメソッドの利点は、たとえば、Object.createlibsを使用しているのでjQueryの.extendメソッドよりも実際にはわかりません。

于 2012-08-08T07:28:15.310 に答える