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.
What’s happening is that
nameis 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:…it is equivalent to writing:
But when you do:
…you are assigning to the
nameproperty of the object, and not to thenewMethodproperty. The variable that you passed under the parameternameis not referenced at all in the above statement.The syntax that would preform the assignment you expect is:
But you cannot express that using dot notation and the
namevariable (except perhaps by cheating and using string concatenation andeval()). In such a case you have to use the array-subscript notation instead.