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

Is there a difference between the two codes below, I suppose 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;
+5
source share
4 answers

There is a difference, at least if you assign a non-primitive object to this.somevaror prototype.somevar.

Try the following:

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');
+2
source

No. 'prototype' used to implement inheritance in Javascript. For example:

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

You can find the source code and additional information here: http://www.prototypejs.org/learn/class-inheritance

+1
source

, . , , Agent. , , .

runtime javascript , Agent. ( ,...)

0

, , . , , ( ), .

0

All Articles