4

次のコードがあるとしましょう。

var A = {a:10};
var B = {b:20};
B.prototype = A;
alert(B.a);

Ba に対して未定義になっています。私は何か間違ったことをしていますか?オブジェクトリテラルのプロトタイプを設定するにはどうすればよいですか?

Constructor オブジェクトの操作方法を知っています。したがって、次のコードは完璧に機能します

function A(){this.a=10}
function B(){this.b=20}
B.prototype = new A();
b = new B;
alert(b.a);

オブジェクトリテラルの場合はどうすればよいですか?

4

3 に答える 3

12

オブジェクトは、自身のプロパティではなく、コンストラクタのプロトタイプ プロパティから継承します。[[Prototype]]コンストラクターのプロトタイプは、一部のブラウザーでプロパティとして使用できる内部プロパティに割り当てられ__proto__ます。

したがって、bから継承するには、の継承チェーンaを置く必要があります。ab

古典的なプロトタイプの継承:

var a = {a: 'a'};
function B(){}
B.prototype = a;

var b = new B();
alert(b.a); // a

ES5 Object.create の使用:

var a = {a: 'a'};
var b = Object.create(a);

alert(b.a); // a

Mozilla の使用__proto__:

var a = {a: 'a'};
var b = {};
b.__proto__ = a;

alert(b.a); // a
于 2013-03-18T09:18:18.143 に答える
3

プロトタイプ プロパティは、通常、Function オブジェクトに存在します。このプロトタイプはオブジェクトである必要があり、このオブジェクトは、コンストラクターで作成されたオブジェクトのプロパティを定義するために使用されます。

// Plain object, no prototype property here.
var plainObject = {one: 1, two: 2};

// Constructor, a prototype property will be created by default
var someConstruct = function() {

  // Constructor property
  someConstruct.constructProp = "Some value";

  // Constructor's prototype method
  someConstruct.prototype.hello = function() {
    return "Hello world!";
  }
};

// Another constructor's prototype method
someConstruct.prototype.usefulMethod = function() {
  return "Useful string";
}

var someInstance = new someConstruct();
console.log(someInstance.hello()); // => Hello world!
console.log(someInstance.usefulMethod()); // => Useful string

console.log(someConstruct.constructProp); // => Some value
console.log(someConstruct.prototype); // => {usefulMethod: function, hello: function}

console.log(plainObject.prototype); // => undefined

したがって、プレーン オブジェクトにはプロトタイプがありません。コンストラクターとして機能する関数には、プロトタイプがあります。これらのプロトタイプは、各構成で作成されたインスタンスを満たすために使用されます。

それが役立つことを願っています:)

于 2013-03-18T08:21:08.280 に答える
0

Functionコンストラクターを使用する場合など、プロトタイプが使用されるオブジェクトを使用する場合のみ。しかし、オブジェクト リテラルにはその必要はありません。

どちらも非常に優れた手法であるため、プロジェクトで何をしたいか、および使用または好みの JavaScript パターンによって異なります。

于 2013-03-18T08:52:02.770 に答える