0

So if I was to create an object literal like this..

var person1 = {

  age : 28,
  name : 'Pete'  }

Then I add a function to the object...

  person1.sayHelloName = function(){

     return 'Hello ' + this.name;

  };

  alert(person1.sayHelloName());

Im wondering where the 'prototype' keyword comes into all this. I cant add a prototype to an object (only to a function constructor) so would I be able/have to use the prototype in this scenario.

Exitos
  • 29,230
  • 38
  • 123
  • 178
  • Sounds similar to [this question](http://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript) – Kyle Jun 14 '11 at 14:50

5 Answers5

1

You don't have to (can) use prototype here. As you have only one instance of something (one object), you can set the functions directly on the object.

FWIW, ECMAScript 5 defines Object.getPrototypeOf with which you can get the protoype of any object (only available in "modern" browsers).

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

You can't use the prototype in this way because, like you say, it's used to add properties to a constructor which must be defined with the function() keyword. What you are doing in your example is extending the person1 object, but that object is just a single variable and not an instantiable class. Meaning you can't "create" another person1 using the new keyword, whereas you could if it were an instance of a defined class.

chrisfrancis27
  • 4,516
  • 1
  • 24
  • 32
1
var Person = function() {
  this.age = 28;
  this.name = "peter";

}

Person.prototype.sayHelloName = function(){
  return 'Hello ' + this.name;
};

var person1 = new Person;
Raynos
  • 166,823
  • 56
  • 351
  • 396
1

You would bring prototype into play to define methods all instances of a class have. In your case that doesn't make any sense since you only create a standalone object that doesn't belong to a class.

function Person (age, name)
{
  this.age = age;
  this.name = name;
}

Person.prototype.sayHelloName = function ()
{
  return 'Hello ' + this.name;
}

person1 = new Person(28,'Pete');
alert(person1.sayHelloName());

This only makes sense of course if you are expecting to be creating more than one person.

Dan
  • 1,878
  • 13
  • 17
1

There's no need for you to use 'prototype' in object literal. Only when you use the constructor pattern (and some other design patterns), that you can use 'prototype'.

Shaoz
  • 10,573
  • 26
  • 72
  • 100
  • you say design pattern, so is that what this is called. Im just wondering when you would decide to use a function constructor and when you would decide to use an object literal? – Exitos Jun 14 '11 at 14:59