So I am reading up on JS with Programming JS applications and JS the goodparts. Reading through objects and functions.. which are apparently the same. According to Crockford himself (and practically everybody). But then I ask: if they are the same then why if I have an object:
var myObject = {
value: 0,
increment: function (inc) {
this.value += inc;
}
};
I can add a function like so:
myObject.double = function () {
this.value += this.value;
}
But when I have a constructor (a function..) :
var myConstructor = function() {
this.value = 0;
this.increment = function(inc){
this.value += inc;
};
};
I cannot add a function like this:
myConstructor.double = function(){
this.value += this.value;
};
But only over the prototype like this:
myConstructor.prototype.double = function(){
this.value += this.value;
};
Now how can anybody say that object and function are the same??
Interestingly, the assignment of the "double" method to the constructor does not give an error, only when you create an object afterwards with new and call the double method on this object does it give: "TypeError can not find".
Also, console.log on the constructor gives:
{ [Function] double: [Function] }
Notice the missing comma between "[Function]" and "double" by the way.. But this probably shows that really functions are actually objects because we just added the double property (a function) to this object.
But then the question becomes... why can I call new on myConstructor and not on myObject ?? How does JS distinguish between them? If they are both objects which can consists of properties, values and functions..?
EDIT: ok, so I get they are not the same, sorry for my imprecise wording. But one question remains: how does JS know the difference between an object with a function property and a constructor to which properties have been added?
var object = {
property : "value",
method: function(){
}
};
console.log(object) outputs to:
{ property: 'asdf', method: [Function] }
and
var myConstructor = function() {
this.property = "value";
this.method = function(inc){
};
};
myConstructor.property = "value";
console.log(myConstructor) outputs to:
{ [Function] property: 'value' }
So if an object has an anonymous function JS knows its a constructor? Or does it know that over the prototype maybe?
myConstructor.double = function(){ this.value += this.value; }in this case your double function like a static function you add it to class function not a object and this references to window object in this case