0

Javascript で継承を行う方法を理解しようとして、Crockfords、Resigs、、、およびその他を含む多くの異なる実装に出くわしPrototypeましklassた。

私が見逃していたのは (大騒ぎに備えて身構えていた)、Smalltalkish の自己/スーパー ペアでした。つまり、現在の「オブジェクト」を表し、のスーパークラスのみのバージョンを参照するselfと同様の役割を果たします。thissuperthis

super[ Smalltalk で何が行われるSubclassかを知っている場合method1は、"]" にスキップしてSuperclassください。これはコードを実行しません。super.method1()Subclass.method2()Subclass.method1()

function Superclass () {
}
Superclass.prototype.method1 = function () {
  return "super";
}

function Subclass () {
}
Subclass.prototype.method1 = function () {
  return "sub";
}
Subclass.prototype.method2 = function () {
  alert (super.method1 ());
}

var o = new Subclass;
o.method2 (); // prints "super"

]

「Javatalk」パッケージはありますか? method2これまでのところ、現在定義されているメソッド ( )のスーパークラス実装へのアクセスを提供する Javascript のオブジェクト指向エミュレーションのみを見てきましたmethod1

ありがとう、のび

4

3 に答える 3

0

superJavaScript で機能を実装するには、非常に多くの方法があります。例えば:

function SuperClass(someValue) {
    this.someValue = someValue;
}

SuperClass.prototype.method1 = function () {
    return this.someValue;
};

function SubClass(someValue) {
    //call the SuperClass constructor
    this.super.constructor.call(this, someValue);
}

//inherit from SuperClass
SubClass.prototype = Object.create(SuperClass.prototype);

//create the super member that points to the SuperClass prototype
SubClass.prototype.super = SuperClass.prototype;

SubClass.prototype.method2 = function () {
    alert(this.super.method1.call(this));
};

var sub = new SubClass('some value');

sub.method2();

編集:

super非標準機能に依存する非常に一般的なメソッドの例を次に示します。私は本当にこれをお勧めしません。これは学習目的としてのみ存在します。

Object.prototype.super = function () {
    var superProto = Object.getPrototypeOf(Object.getPrototypeOf(this)),
        fnName = arguments.callee.caller.name,
        constructorName = this.constructor.name;

    if (superProto == null) throw constructorName + " doesn't have a superclass";
    if (typeof superProto[fnName] !== 'function') {
        throw constructorName + "'s superclass (" 
            + superProto.constructor.name + ") doesn't have a " + fnName + ' function';
    }

    return superProto[arguments.callee.caller.name].apply(
        this, 
        [].slice.call(arguments, 1)
    );
};   


function A() {
}

A.prototype.toString = function toString() {
    //call super method Object.prototype.toString
    return this.super();
};

var a = new A();

console.log(a.toString());
于 2013-09-12T14:10:32.217 に答える
0

簡単に言うと、これは私が今まで読んだ中で最高の JavaScript チュートリアルです。だから私はあなたにそれをお勧めします。幸運を!

于 2013-09-12T13:56:10.127 に答える