I want to add a new method named size to object class in javascript.
var obj = {here: {is: "an"}, object: 2};
object.prototype.size = function() {
var obj=this;
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
console.log(obj.size());
The obj is typeof object, I add new function for object as object.prototype.size=function(){}
But when I run it, the firefox give me error:
ReferenceError: object is not defined (line 10)
you can view the code here:(http://jsbin.com/cisasewo/1/edit)
When I change the method to:
Object.prototype.size = function() {
var obj=this;
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
when it invoke, it just give me the function not the answer the size of the function? why? how to add the size function to object class in javascript?