89

私は10年以上OOP言語でプログラミングしてきましたが、今はJavaScriptを学んでおり、プロトタイプベースの継承に遭遇したのはこれが初めてです。私は良いコードを勉強することで最も早く学ぶ傾向があります。プロトタイプの継承を適切に使用するJavaScriptアプリケーション(またはライブラリ)のよく書かれた例は何ですか?そして、プロトタイプの継承がどのように/どこで使用されているかを(簡単に)説明できますか?それで、どこから読み始めればよいかわかりますか?

4

11 に答える 11

75

前述のように、ダグラス・クロックフォードの映画はその理由について良い説明をしており、その方法をカバーしています。しかし、JavaScriptの数行に入れるには:

// Declaring our Animal object
var Animal = function () {

    this.name = 'unknown';

    this.getName = function () {
        return this.name;
    }

    return this;
};

// Declaring our Dog object
var Dog = function () {

    // A private variable here        
    var private = 42;

    // overriding the name
    this.name = "Bello";

    // Implementing ".bark()"
    this.bark = function () {
        return 'MEOW';
    }  

    return this;
};


// Dog extends animal
Dog.prototype = new Animal();

// -- Done declaring --

// Creating an instance of Dog.
var dog = new Dog();

// Proving our case
console.log(
    "Is dog an instance of Dog? ", dog instanceof Dog, "\n",
    "Is dog an instance of Animal? ", dog instanceof Animal, "\n",
    dog.bark() +"\n", // Should be: "MEOW"
    dog.getName() +"\n", // Should be: "Bello"
    dog.private +"\n" // Should be: 'undefined'
);

ただし、このアプローチの問題は、オブジェクトを作成するたびにオブジェクトが再作成されることです。別のアプローチは、次のように、プロトタイプスタックでオブジェクトを宣言することです。

// Defining test one, prototypal
var testOne = function () {};
testOne.prototype = (function () {
    var me = {}, privateVariable = 42;
    me.someMethod = function () {
        return privateVariable;
    };

    me.publicVariable = "foo bar";
    me.anotherMethod = function () {
        return this.publicVariable;
    };

    return me;

}());


// Defining test two, function
var testTwo = ​function() {
    var me = {}, privateVariable = 42;
    me.someMethod = function () {
        return privateVariable;
    };

    me.publicVariable = "foo bar";
    me.anotherMethod = function () {
        return this.publicVariable;
    };

    return me;
};


// Proving that both techniques are functionally identical
var resultTestOne = new testOne(),
    resultTestTwo = new testTwo();

console.log(
    resultTestOne.someMethod(), // Should print 42
    resultTestOne.publicVariable // Should print "foo bar"
);

console.log(
    resultTestTwo.someMethod(), // Should print 42
    resultTestTwo.publicVariable // Should print "foo bar"
);



// Performance benchmark start
var stop, start, loopCount = 1000000;

// Running testOne
start = (new Date()).getTime(); 
for (var i = loopCount; i>0; i--) {
    new testOne();
}
stop = (new Date()).getTime();

console.log('Test one took: '+ Math.round(((stop/1000) - (start/1000))*1000) +' milliseconds');



// Running testTwo
start = (new Date()).getTime(); 
for (var i = loopCount; i>0; i--) {
    new testTwo();
}
stop = (new Date()).getTime();

console.log('Test two took: '+ Math.round(((stop/1000) - (start/1000))*1000) +' milliseconds');

イントロスペクションに関しては、わずかな欠点があります。testOneをダンプすると、有用性の低い情報になります。また、「testOne」のプライベートプロパティ「privateVariable」はすべてのインスタンスで共有されており、shesekによる返信で参考になっています。

于 2012-11-14T13:41:00.393 に答える
48

Douglas Crockfordには、 JavaScriptのプロトタイプの継承に関するすばらしいページがあります。

5年前、私はJavaScriptでClassicalInheritanceを作成しました。JavaScriptはクラスフリーのプロトタイプ言語であり、古典的なシステムをシミュレートするのに十分な表現力があることを示しました。それ以来、私のプログラミングスタイルは進化してきました。優れたプログラマーなら誰でもそうです。私は原型主義を完全に受け入れることを学び、古典的なモデルの範囲から自分自身を解放しました。

Dean EdwardのBase.jsMootoolsのClass、またはJohnResigのSimpleInheritanceの作品は、JavaScriptで古典的な継承を行う方法です。

于 2010-01-19T16:56:53.757 に答える
26
function Shape(x, y) {
    this.x = x;
    this.y = y;
}

// 1. Explicitly call base (Shape) constructor from subclass (Circle) constructor passing this as the explicit receiver
function Circle(x, y, r) {
    Shape.call(this, x, y);
    this.r = r;
}

// 2. Use Object.create to construct the subclass prototype object to avoid calling the base constructor
Circle.prototype = Object.create(Shape.prototype);
于 2014-04-15T15:21:22.343 に答える
14

YUIとDeanEdwardのBaseライブラリを見てみましょう:http: //dean.edwards.name/weblog/2006/03/base/

YUIの場合は、特にlangモジュールを簡単に確認できます。YAHOO.lang.extendメソッド。次に、いくつかのウィジェットまたはユーティリティのソースを参照して、それらがそのメソッドをどのように使用しているかを確認できます。

于 2010-01-14T14:33:29.230 に答える
5

MicrosoftのASP.NETAjaxライブラリ(http://www.asp.net/ajax/ )もあります。

オブジェクト指向技術を使用した高度なWebアプリケーションの作成など、MSDNに関する優れた記事もたくさんあります。

于 2010-01-14T14:38:06.900 に答える
5

これは、Mixuのノードブック( http://book.mixu.net/node/ch6.html)から私が見つけた最も明確な例です。

私は継承よりも構成を好みます:

構成-オブジェクトの機能は、他のオブジェクトのインスタンスを含むことにより、さまざまなクラスの集合体で構成されます。継承-オブジェクトの機能は、それ自体の機能とその親クラスの機能で構成されます。継承が必要な場合は、プレーンな古いJSを使用してください

継承を実装する必要がある場合は、少なくとも別の非標準の実装/魔法の関数を使用しないでください。純粋なES3で継承の合理的な複製を実装する方法は次のとおりです(プロトタイプでプロパティを定義しないという規則に従う限り)。

function Animal(name) {
  this.name = name;
};
Animal.prototype.move = function(meters) {
  console.log(this.name+" moved "+meters+"m.");
};

function Snake() {
  Animal.apply(this, Array.prototype.slice.call(arguments));
};
Snake.prototype = new Animal();
Snake.prototype.move = function() {
  console.log("Slithering...");
  Animal.prototype.move.call(this, 5);
};

var sam = new Snake("Sammy the Python");
sam.move();

これは古典的な継承と同じものではありませんが、標準で理解しやすいJavascriptであり、チェーン可能なコンストラクターとスーパークラスのメソッドを呼び出す機能など、人々が主に求める機能を備えています。

于 2016-01-12T02:28:06.263 に答える
5

ES6classおよびextends

ES6はclassextends以前に可能だったプロトタイプチェーン操作の単なるシンタックスシュガーであり、おそらく最も標準的なセットアップです。

まず、プロトタイプチェーンと.プロパティルックアップの詳細については、 https ://stackoverflow.com/a/23877420/895245をご覧ください。

それでは、何が起こるかを分解してみましょう。

class C {
    constructor(i) {
        this.i = i
    }
    inc() {
        return this.i + 1
    }
}

class D extends C {
    constructor(i) {
        super(i)
    }
    inc2() {
        return this.i + 2
    }
}
// Inheritance syntax works as expected.
(new C(1)).inc() === 2
(new D(1)).inc() === 2
(new D(1)).inc2() === 3
// "Classes" are just function objects.
C.constructor === Function
C.__proto__ === Function.prototype
D.constructor === Function
// D is a function "indirectly" through the chain.
D.__proto__ === C
D.__proto__.__proto__ === Function.prototype
// "extends" sets up the prototype chain so that base class
// lookups will work as expected
var d = new D(1)
d.__proto__ === D.prototype
D.prototype.__proto__ === C.prototype
// This is what `d.inc` actually does.
d.__proto__.__proto__.inc === C.prototype.inc
// Class variables
// No ES6 syntax sugar apparently:
// https://stackoverflow.com/questions/22528967/es6-class-variable-alternatives
C.c = 1
C.c === 1
// Because `D.__proto__ === C`.
D.c === 1
// Nothing makes this work.
d.c === undefined

すべての事前定義されたオブジェクトのない簡略図:

      __proto__
(C)<---------------(D)         (d)
| |                |           |
| |                |           |
| |prototype       |prototype  |__proto__
| |                |           |
| |                |           |
| |                | +---------+
| |                | |
| |                | |
| |                v v
|__proto__        (D.prototype)
| |                |
| |                |
| |                |__proto__
| |                |
| |                |
| | +--------------+
| | |
| | |
| v v
| (C.prototype)--->(inc)
|
v
Function.prototype
于 2016-11-20T13:11:54.700 に答える
1

PrototypeJSのClass.createを確認することをお勧めします:
83行目@ http://prototypejs.org/assets/2009/8/31/prototype.js

于 2010-01-21T13:29:06.063 に答える
0

私が見た中で最も良い例は、ダグラス・クロックフォードのJavaScript: TheGoodPartsにあります。言語についてバランスの取れた見方をするために購入する価値は間違いありません。

Douglas CrockfordはJSON形式を担当し、YahooでJavaScriptの第一人者として働いています。

于 2010-01-22T19:59:50.813 に答える
0

ECMAScriptバージョン固有の実装を備えたスニペットJavaScriptプロトタイプベースの継承があります。現在のランタイムに応じて、ES6、ES5、ES3のいずれの実装を使用するかが自動的に選択されます。

于 2015-05-28T08:13:25.347 に答える
0

Javascriptでのプロトタイプベースの継承の例を追加します。

// Animal Class
function Animal (name, energy) {
  this.name = name;
  this.energy = energy;
}

Animal.prototype.eat = function (amount) {
  console.log(this.name, "eating. Energy level: ", this.energy);
  this.energy += amount;
  console.log(this.name, "completed eating. Energy level: ", this.energy);
}

Animal.prototype.sleep = function (length) {
  console.log(this.name, "sleeping. Energy level: ", this.energy);
  this.energy -= 1;
  console.log(this.name, "completed sleeping. Energy level: ", this.energy);
}

Animal.prototype.play = function (length) {
  console.log(this.name, " playing. Energy level: ", this.energy);
  this.energy -= length;
  console.log(this.name, "completed playing. Energy level: ", this.energy);
}

// Dog Class
function Dog (name, energy, breed) {
  Animal.call(this, name, energy);
  this.breed = breed;
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Dog.prototype.bark = function () {
  console.log(this.name, "barking. Energy level: ", this.energy);
  this.energy -= 1;
  console.log(this.name, "done barking. Energy level: ", this.energy);
}

Dog.prototype.showBreed = function () {
  console.log(this.name,"'s breed is ", this.breed);
}

// Cat Class
function Cat (name, energy, male) {
  Animal.call(this, name, energy);
  this.male = male;
}

Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;

Cat.prototype.meow = function () {
  console.log(this.name, "meowing. Energy level: ", this.energy);
  this.energy -= 1;
  console.log(this.name, "done meowing. Energy level: ", this.energy);
}

Cat.prototype.showGender = function () {
  if (this.male) {
    console.log(this.name, "is male.");
  } else {
    console.log(this.name, "is female.");
  }
}

// Instances
const charlie = new Dog("Charlie", 10, "Labrador");
charlie.bark();
charlie.showBreed();

const penny = new Cat("Penny", 8, false);
penny.meow();
penny.showGender();

ES6は、コンストラクターとスーパーキーワードを使用することで、はるかに簡単な継承の実装を使用します。

于 2019-07-15T14:50:53.050 に答える