2

I've been learning Js recently from "JavaScript the Good Parts", and according to my understanding

Object.propertyName yields same result as Object["propertyName"](Please correct me if I'm not right and describe the difference of the two).

I'm trying to augment the Function.prototype to make a method available to all functions as below:

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

And it's working fine.However, when I'm replacing the this.prototype[name] with this.prototype.name, it'll fail functioning as expected!

This is how I'm testing it:

 Number.method("myRoundFunction", function () {
        return Math[this < 0 ? "ceil" : "floor"](this);
    });
    console.log((-10 / 3).myRoundFunction());

This shows the expected value (-3) when using this.prototype[name], but

(-3.3333333333333335).myRoundFunction is not a function

on changing it to this.prototype.name

Could someone possibly clarify why this is happening?

Thanks in advance for any help.

Amir
  • 9,577
  • 11
  • 41
  • 58

3 Answers3

4

What's happening is that name is a variable, and cannot be used directly with dot notation. To better illustrate the issue, let's say you pass a value of "newMethod" for name. Now when you do:

this.prototype[name] = func;

...it is equivalent to writing:

this.prototype["newMethod"] = func;

But when you do:

this.prototype.name = func;

...you are assigning to the name property of the object, and not to the newMethod property. The variable that you passed under the parameter name is not referenced at all in the above statement.

The syntax that would preform the assignment you expect is:

this.prototype.newMethod = func;

But you cannot express that using dot notation and the name variable (except perhaps by cheating and using string concatenation and eval()). In such a case you have to use the array-subscript notation instead.

aroth
  • 54,026
  • 20
  • 135
  • 176
3

Prototype defines the JS classes definition; whereas something like Number.parse is a direct function on a type (similar to a static method). If I do:

myclass.prototype["name"] = function() { }

I'm adding a method to the next instance of the class, whereas:

myclass["name"] = function() { }

Adds the function directly to the class object, not to the next instance of myclass. I think this is what's happening when I see the definition of Number.method?

Or am I missing something?

Brian Mains
  • 50,520
  • 35
  • 148
  • 257
2

name is a variable, when you use this.prototype.name, it is the same as you call this.prototype["name"], not what you think as this.prototype[name].

ijse
  • 2,998
  • 1
  • 19
  • 25