3

これは非常に古いテーマであり、多くのことが書かれていますが、正確にこのスピンを見つけていないので、ご容赦ください.

少し時間をかけて JavaScript のnewandf.prototypeコンストラクター構造について頭を悩ませ、それがどのようにプロトタイプ言語であるかについて読んだ後、この件に関する Crockford の啓発的なコメントは言うまでもなく、次のことが非常に重要であるという結論に達しました。 JavaScript で従来のクラスベースの継承をシミュレートするより自然な方法:

// emphasise that there's no superclass instead of writing A = {}
var A = Create.object(null);

// define the 'instance initializer', which half of what a constructor is
A.init = function(x, y) {
    this.x = x;
    this.y = y;
    return this;
}

// a method
A.sum = function() {
    return this.x + this.y;
}

// instantiate A
var a = Object.create(A).init(3);

// a subclass
var B = Object.create(A);

B.init = function(x, y, w) {
    A.init.call(this, x, y);
    this.w = w;
    return this;
}

B.weightedSum = function() {
    return (1.0 - this.w) * this.x + this.w * this.y;
}

// instantiate B
var b = Object.create(B).init(1, 2, 0.3);

// equivalent of `instanceof`
var bInstanceOfA = A.isPrototypeOf(b);

これについて私が気に入っているのは、オブジェクトの作成 (インスタンス化とサブクラス化の両方に適用される) と初期化 (インスタンス化にのみ適用される) が明確に分離されているため、実際に何が起こっているのかを明らかにすることです。また、基本クラスとサブクラスの作成には対称性があります。このコードは、外部で定義された関数やライブラリを必要としませんが、特に冗長でもありません。

したがって、私の質問は次のとおりです。JavaScript の経験が豊富な方は、私が考慮していないアプローチに問題があるかどうか、またはそれが良いパターンであるかどうか教えていただけますか?

4

1 に答える 1

0

newこのアプローチではキーワードを失います。だからあなたは言うことができませんnew A(128, 256)

ただしObject.create()、プロトタイプの継承に使用してnew、この方法でキーワードを使用して通常のオブジェクトを作成できます。

var Employee = function(name) {
    this.name = name;
    return this;
};

Employee.prototype = {
    doWork: function() {
        console.log('%s is doing some abstract work', this.name);
    }
};

var Driver = function(name) {
    return Employee.call(this, name);
};

Driver.prototype = Object.create(Employee.prototype, {
    doWork: {
        value: function() {
            console.log('%s is driving a car', this.name);
        }
    },
    fixEngine: {
        value: function() {
            console.log('%s is fixing an engine', this.name);
        }
    }
});

var employee = new Employee('Jim');
var driver = new Driver('Bill');

employee.doWork(); // Jim is doing some abstract work 
driver.doWork(); // Bill is driving a car
driver.fixEngine(); // Bill is fixing an engine 

http://jsfiddle.net/f0t0n/HHqEQ/

于 2013-10-22T11:23:11.567 に答える