开发者

Is there a difference between using "this" and "prototype" in Javascript here?

Is there a difference between the two codes below, I presume not.

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

    this.isActive = true;
    this.isMale = false;
}
开发者_运维技巧

and

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

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


There is a difference at least if you are assigning a non-primitive object to this.somevar or prototype.somevar.

Try running this:

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');


No. 'prototype' used for implementing inheritance in Javascript. Such as that:

/** 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!"

code source and additional info you can find here: http://www.prototypejs.org/learn/class-inheritance


Functionally, this is the same. The latter, however, emphasizes similarities between Agent objects. You can see in a glimpse that these members have that value, while in a more complicated constructor function, with lots of conditionals, it's harder.

It also allows the javascript runtime to choose how it handles Agent member initializations. (do some precompilation, ...)


Assuming that this function is to be used as a constructor, the first with set properties on the new instance and the second on the prototype. If they are independent of the instance the two snippets are equivalent, but if they aren't (as their name suggest), then they are not.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜