5

下面的两个代码有区别吗,我想没有。

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.somevaror ,则存在差异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

No. 'prototype' 用于在 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

假设这个函数被用作构造函数,第一个在新实例上设置属性,第二个在原型上。如果它们独立于实例,则这两个片段是等效的,但如果它们不是(如其名称所示),那么它们不是。

于 2009-11-17T11:40:39.187 回答