In Javascript every function is an object.
function a() {
this.x = function() { console.log("x"); }
}
Here "a" is a function, which is an object. right?
var b = Object.create(a);
b.x(); //does not work!!
The above code would work if we wrote -
var b = Object.create(new a())
So does that mean only the instance of a function is an object? not the function?
4 Answers 4
They are not instance of functions you are messing with the new keyword the new keywords does many things:
- A brand new object is created
- The new object is [[prototype]]-linked
- The new object is set as the 'this' binding for the function call
- Unless the function returns its own object the newly invoked call function will return the new object
In your first example you are creating an object from function a which does not have any x property.
In the last you are creating and object of the object returned by the new a() invocation which has a x property because it is asigned in the execution of the a function
1 Comment
function a() {
this.x = function() { console.log("x"); }
}
var b = new a();
b.x();
A function is like a class. You can create instances or objects using the new keyword.
4 Comments
new creates an instance.What this is depends on how you use your a function. If you don't run it as a constructor function (you don't use a new keyword), this points to the outer scope. Try this:
function a() {
this.x = function() { console.log("x"); }
}
a();
console.log(window.x());
On the other hand, when you write new a(), you are running it as a constructor function, in which case this points to the instance of newly created object. Try now this example:
function a() {
this.x = function() { console.log("x"); }
}
var b = new a(); // mind the "new" keyword here
console.log(b.x());
console.log(window.x);
And as a simplest proof that every function is an object:
function c() {};
c instanceof Object; // ;-)
Comments
Every function is a class not an object, every function value is an object. A class is a set of objects and a function is a set of function values, therefore every function is a class and in the spirit of pure functional programming, every function value is an object.
thisis not that object. It is the context set by the caller.avariable does not havexproperty :-) so and inheritedbalso does not have itthisnot a reference toa, in the code that didn't work you never actually call the function so the code inside it hasn't been run.