0

Here is my code for adding a method in a javascript object. I searched a lot but nothing worked for me. What's wrong??

<!DOCTYPE html>
<html>
<body>

<script>

var person = new Object();

person.prototype.display=function(){

alert("ok");

}

person.display();

</script>
</body>


</html>
Geek Num 88
  • 5,264
  • 2
  • 22
  • 35
John
  • 339
  • 2
  • 7
  • 17

3 Answers3

0

You can't add a property to undefined.

var foo = new Object();
foo.prototype; // undefined
Object.getPrototypeOf(foo); // prototype of all objects

To create an Object with it's own prototype, use Object.create

var proto = {},
    foo = Object.create(proto);
foo.prototype; // still undefined
Object.getPrototypeOf(foo) === proto; // true

Alternatively, use new with a dummy function

var Obj = function () {},
    proto = Obj.prototype = {};
var foo = new Obj;
foo.prototype; // again still undefined
Object.getPrototypeOf(foo) === proto; // true

Once you have the prototype from these last two, you can use it as normal

proto.display = function () {console.log('display');};
foo.display();
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • Can you please help me with my example...I amnew to javascript and I feel like I am lost.. – John Aug 28 '13 at 15:56
  • Choose either code block `2` or `3` from my answer and rename `foo` to `person`, then copy code block `4` and change the _function_ to the action you want. – Paul S. Aug 28 '13 at 15:58
0

Try this:

function person() {}
person.prototype.display = function(){ alert("ok"); } 
var p = new person();
p.display();

EDITED to fix syntax error.

zigdawgydawg
  • 2,046
  • 13
  • 10
  • This does work.But why it did not without a constructor..?? – John Aug 28 '13 at 15:59
  • 1
    `function person() {}` creates a first-class object whereas `new Object();` does not. You can only access the the properties of the prototype from a first class object. This explanation is more detailed: [stack overflow](http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work) – zigdawgydawg Aug 28 '13 at 16:04
0

If you are trying to implement prototypical inheritance in javascript 'person' needs to be a function, not an object.

This is a good intro I think - http://alexsexton.com/blog/2013/04/understanding-javascript-inheritance/.

quoo
  • 6,237
  • 1
  • 19
  • 36
  • The above code worked just fine..There was a constructor and then everything was set.. What is the difference between a custom object and the root one..? – John Aug 28 '13 at 16:03
  • The code 'var foo = new Object()' is essentially the same as saying 'var foo = {}'. There's no prototype property in either, if that makes more sense? – quoo Aug 28 '13 at 16:16
  • Thank you.That one was good.. – John Aug 28 '13 at 16:58