5

以下の 2 つのコードに違いはありますか。

function Agent(bIsSecret)
{
    if(bIsSecret)
        this.isSecret=true;

    this.isActive = true;
    this.isMale = false;
}

function Agent(bIsSecret)
{
    if(bIsSecret)
        this.isSecret=true;
}

Agent.prototype.isActive = true;    
Agent.prototype.isMale = true;
4

4 に答える 4

2

this.somevarまたはに非プリミティブ オブジェクトを割り当てている場合は、少なくとも違いがありますprototype.somevar

これを実行してみてください:

function Agent(bIsSecret)
{
    if(bIsSecret)
        this.isSecret=true;

    this.isActive = true;
    this.isMale = false;
    this.myArray = new Array(1,2,3);
}

function Agent2(bIsSecret)
{
    if(bIsSecret)
        this.isSecret = true;
}

Agent2.prototype.isActive = true;    
Agent2.prototype.isMale = true;
Agent2.prototype.myArray = new Array(1,2,3);

var agent_a = new Agent();
var agent_b = new Agent();

var agent2_a = new Agent2();
var agent2_b = new Agent2();

if (agent_a.myArray == agent_b.myArray) 
    alert('agent_a.myArray == agent_b.myArray');
else
    alert('agent_a.myArray != agent_b.myArray');

if (agent2_a.myArray == agent2_b.myArray) 
    alert('agent2_a.myArray == agent2_b.myArray');
else
    alert('agent2_a.myArray != agent2_b.myArray');
于 2009-11-17T11:44:28.367 に答える
1

いいえ。Javascriptで継承を実装するために使用される「プロトタイプ」。そのような:

/** obsolete syntax **/

var Person = Class.create();
Person.prototype = {
  initialize: function(name) {
    this.name = name;
  },
  say: function(message) {
    return this.name + ': ' + message;
  }
};

var guy = new Person('Miro');
guy.say('hi');
// -> "Miro: hi"

var Pirate = Class.create();
// inherit from Person class:
Pirate.prototype = Object.extend(new Person(), {
  // redefine the speak method
  say: function(message) {
    return this.name + ': ' + message + ', yarr!';
  }
});

var john = new Pirate('Long John');
john.say('ahoy matey');
// -> "Long John: ahoy matey, yarr!"

ここで見つけることができるコードソースと追加情報:http://www.prototypejs.org/learn/class-inheritance

于 2009-11-17T11:39:35.157 に答える
0

機能的には、これは同じです。ただし、後者はAgentオブジェクト間の類似性を強調します。これらのメンバーがその値を持っていることが一目でわかりますが、条件がたくさんあるより複雑なコンストラクター関数では、それはより困難です。

また、javascriptランタイムがAgentメンバーの初期化を処理する方法を選択できるようにします。(いくつかのプリコンパイルを行います、...)

于 2009-11-17T11:39:53.823 に答える
0

この関数がコンストラクターとして使用されると仮定すると、最初の関数は新しいインスタンスにプロパティが設定され、2番目の関数はプロトタイプに設定されます。それらがインスタンスから独立している場合、2つのスニペットは同等ですが、そうでない場合(名前が示すように)、そうではありません。

于 2009-11-17T11:40:39.187 に答える