tags:

views:

89

answers:

2

I have been trying some fundamentals in javascript and here is what I observed.

I wrote a prototype modification method for Function object

Function.prototype.method = function(name, func)
{
   this.prototype[name] = func;
   return this;
}

function pirates(value)
{
   console.log("I just throw away the value!!" + value);
}

pirates.method("my_skill", function(){
   console.log("Pirate skills");
});

new_pirate = new pirates(1234);

//SUCCESS
new_pirate.my_skill(); //prints "Pirate skills"

var someCrappyVariable = function(){
  return function()
  {
     console.log("I am going to just sit and do nothing. Really!");
  }
}();

**//Throws error. WHY???????? This was assigned a function, so ideally prototype should work on this too? Shouldn't it?**
someCrappyVariable.method("crappyFunction", function(){
   console.log("am I doomed?");
});

Why does last assignment throws an error that someCrappyVariable is not a function, when it was assigned a function reference earlier? I am confused.

Cheers

+2  A: 

Your code should be throwing an error here:

new_pirate.method("my_skill", function(){
   console.log("Pirate skills");
});
// TypeError: new_pirate.method is not a function

... since method is not a direct or inherited method. The object created from new pirates(1234) will not inherit from Function; it will inherit from Object (which, ideally, shouldn't be extended with custom methods).

J-P
It doesn't work as described. It really throws an error on "my_skill".
artificialidiot
That bit is right. So do I assume that problem with my someCrappyVariable also not being able to inherit the prototype method is that, that it's inheriting from object and not from function..Why does it inherit from object? Did we not assign a function to it?
Priyank
new invokes a function as a constructor method over a newly created object. There is one more error in your code which I'm gonna post as an answer.
artificialidiot
A: 

If we remove the code for "new_pirate", there is still an error.

In standard js, a prototype chain for an object can be established by assigning the prototype property of the constructor before it runs and creates the object. So if you call the "method" on someCrappyVariable, it will set the "name" on the "prototype" property of the created object only, which is pretty much useless.

What you actaully want is to set someCrappyVariable.constructor.prototype[name] so all object with the same constructor can find the set method like someCrappyVariable[name] (which is created by an anonymous function in this case).

artificialidiot