In the book Javascript: The good parts the author uses following code to create objects
if (typeof Object.create !== 'function') {
Object.create = function (o) {
var F = function () {};
F.prototype = o;
return new F();
};
}
var another_stooge = Object.create(stooge);
The function is meant to create an object but it returns a function instead. (Reference - Chapter 3, Page number : 22)
1 Answer 1
Is there no difference between function and objects in javascript?
Functions are objects that can be called, and they're created with different syntax.
The author uses following code to create objects [...]
We should no more. Object.create is standardised and implemented in about every browser.
Anyway, we should not try to understand what Object.create does by looking at this horrible polyfill. We should treat Object.create as a langauge primitive (and we can define the new operator in terms of it if we want).
The function is meant to create an object but it returns a function instead.
No, it doesn't. It does not return F, it does return new F(), which is the result of a call to F (as a constructor).
Object.createreturns a new instance of the object passed into it.Object.crearereturnsF()which is a functionnew F(). Please read the documentation for Object.create and the new keyword.