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
?
-
1I'm not sure what you mean by "functional object." As opposed to what? – Explosion Pills Feb 19 '13 at 15:49
-
Why? because JavaScipt. :) – DanC Feb 19 '13 at 15:50
-
@Explosion Pills , This word is used in the question that I referred ,have a look on that. – Anshul Feb 20 '13 at 07:05
3 Answers
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.

- 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
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

- 1
- 1

- 72,912
- 30
- 168
- 299
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".