2
    function Obj1(name){
        this.__proto__={
            Name:name,
            getName:function(){
                alert(this.Name); 
            }


        };

    }

    function Obj2(name){
       this.prototype={
           Name:name,
           getName:function(){
           alert(this.Name); 
           };


       };

    }
    x=new Obj1("blue shark");
    z=new Obj2("red shark");
    x.getName();
    z.getName();// error:z.getName() is not a function

What is the difference between the two?Some say prototype is used for constructor functions only but in this case it doesn't work.... instead the __proto__ work why?

rene
  • 41,474
  • 78
  • 114
  • 152
  • It makes very little sense to set the prototype inside the constructor function. Furthermore __proto__ is not part of the ecma standard. – mpm May 06 '13 at 08:22
  • [Not yet](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-B.3.1), anyway. – Dagg Nabbit May 06 '13 at 08:24
  • possible duplicate of [\_\_proto\_\_ Vs. prototype in JavaScript](http://stackoverflow.com/questions/9959727/proto-vs-prototype-in-javascript) – Bergi Jan 23 '14 at 22:16

3 Answers3

5

__proto__ (which is not standard (but might be soon))) sets an object's prototype.

.prototype sets the prototype of objects created by invoking the function it was set on as a constructor using new

Also worth mentioning is Object.create

Here are examples:

Pseudo-classical with .prototype:

function Car(){
   this.x = 15;
}
Car.prototype.y = 10;

var g = new Car();
g.y; // this is 10;

Using __proto__ (don't use this!):

var g = {x:15};
g.__proto__ = {y:10};
g.y; // this is 10;

This way is correct, and does not use constructors with new:

var g = Object.create({y:10}); //creates x with prototype {y:10}
g.x = 15;
g.y; // this is 10

Here is an interesting tutorial on MDN covering these.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
2

Only functions has the property prototype. You need to set the prototype on the function self.

function Obj2(name){
    this.name = name;
}

Obj2.prototype={
    getName:function(){
       alert(this.Name); 
    }
};
xdazz
  • 158,678
  • 38
  • 247
  • 274
2

__proto__ is not a standard property.

Anyway every object created by new will get a prototype from the .prototype member of the constructor (a function). Note that the prototype member has no name, you cannot access it directly, you need Object.getPrototypeOf(x).

If you want to create an object with a given prototype the code is Object.create(proto) that is more or less equivalent to

function makeObjectWithPrototype(x) {
    function makeit() { }
    makeit.prototype = x;
    return new makeit();
}
6502
  • 112,025
  • 15
  • 165
  • 265
  • 2
    That's Crockford's old BEGET function :) With modern JS you can use `Object.create` instead (which has other benefits). Also, you can get an object's prototype using the standard `Object.getPrototypeOf` – Benjamin Gruenbaum May 06 '13 at 08:37