If you open this JSFiddle, you should see in Firebug/Chrome Dev Tools that an exception is thrown when x.method is called, as method does not exist.
However if you run either Object.method or Function.method in the console you’ll see that they do indeed exist in their respective prototypes.
I’m sure its a simply inheritence issue, but its beyond me at this point as to why the method method isn’t bubbling up to the x Object.
The code is as follows:
// Crockford's Object.create shim
if (typeof Object.create !== 'function') {
Object.create = function (o) {
var F = function () {};
F.prototype = o;
return new F();
};
}
// Add a method creation function to the Function prototype
// Note that on this line I've also tried:
// Object.prototype.method = Function.prototype.method = function (name, func) {
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
// Create our object
var x = Object.create({});
// Add common methods to the prototype of our new object
x.method('logNumber', function (num) {
console.log(num);
});
// Try it out
x.logNumber(6);
[note] jsfiddle seems to be down at the moment, so I couldn’t check your code
This function:
adds a method to the Function prototype. An Object is created using a constructor function: a function that, called with the
newkeyword, will create instances of the Object it constructs. In theObject.create‘shim’ the constructor function isF, but the shim returns an instance of it (new F()).Variable
xis not a constructor Function, but an instance. You can only callmethodfrom Function.prototype, sox.methodisundefined.Not using
Object.createmay show you how it works: