TypeError: this.prototype undefined when calling the .prototype.method () function

I read the book "Javascript: the good parts."
Now I am reading a chapter on additional types:

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

UPDATE:
Why is the following code not working?

js> Function.prototype.method("test", function(){print("TEST")});
typein:2: TypeError: this.prototype is undefined

But the following code works without problems:

js> Function.method("test", function(){print("TEST")});
function Function() {[native code]}

Why does this code work?

js> var obj = {"status" : "ST"};
js> typeof obj;
"object"
js> obj.method = function(){print(this.status)};
(function () {print(this.status);})
js> obj.method();
ST

"obj" is an object.
But I can call the method "method" on it.
What is the difference between Function.prototype.method and obj.method?

+5
source share
3 answers

thisrefers to Function.prototypebecause you called .method. So you use Function.prototype.prototypeone that does not exist.

Function.method(...) this[name] = ... .prototype s.

+5

:

Function instanceof Function           // <--- is true
Function.prototype instanceof Function // <-- is false
  • Function.prototype Function.
  • Function - , , Function.prototype.

  • Function.method method Function. , this Function.
  • Function.prototype.method . this Function.prototype.

, :

Function.method()                // is equivalent to
(function Function(){}).method()
(new Function).method()          // Because Function is also a function

Function.prototype.method // No instance, just a plain function call
+5

, . , .

0

All Articles