0

As I can see in the question 'How does JavaScript .prototype work?' the correct way to use the prototype property is with a functional object. But I am not able to understand why we need a functional object to use prototype?

Community
  • 1
  • 1
Anshul
  • 9,312
  • 11
  • 57
  • 74

3 Answers3

1

As mentioned in the question you referred

var obj = new Object(); // not a functional object
obj.prototype.test = function() { alert('Hello?'); }; // this is wrong!

That's because Object is the base class for all.

function MyClass() {

}
var obj = new MyClass();

// it returns true even though its an instance of MyClass
console.log(obj instanceof Object);

If you add a prototype function to Object class, you need to make sure that its non-enumerable.

Salman
  • 9,299
  • 6
  • 40
  • 73
  • Of course you can add prototype methods to `Object`! However, you need to care about making them non-enumerable. – Bergi Feb 19 '13 at 16:20
1

When you create a function in JavaScript, the interpreter automatically creates a prototype object for it. This is because functions can be used as constructors.

Only functions and no other object can be used as a constructor.

That's the reason only functions have a prototype property. The prototype property of a function is very special. Instances of that function will have the prototype of the function in their __proto__ chain.

Read this answer for more details: https://stackoverflow.com/a/8096017/783743

Community
  • 1
  • 1
Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
1

why we need a functional object for prototype?

It was an odd(?) language design decision in early JS versions. Yet this was fixed with EcmaScript 5: Object.create allows us to do prototypical inheritance without constructor functions. So if you don't need an initialisation function (as a closure for example), you happily can use "Object.create" instead of "new".

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375