How flexible is JavaScript?
JavaScript is a flexible language with strong expressiveness. Let me give you an example to surprise many people.
This article was inspired by Kyle Simpson's article Iterating ES6 Numbers.
First, deploy an add method on the Number. prototype object.
Number.prototype.add = function (x) { return this + x;};
The code above defines an add method for the Number instance. If you are not familiar with this writing method, we recommend that you read my JavaScript object-oriented programming.)
Because the Number instance is a numeric value, calling a method on the numeric value will automatically convert the numeric value to the instance object, so the following result is obtained.
8['add'](2)// 10
In the code above, the calling method is written8['add']Instead8. addIt is because the vertex after the value is interpreted as the decimal point rather than the vertex operator.
Place the value in parentheses and you can use the dot operator to call the method.
(8) .add (2)// 10
In fact, there is another way of writing.
8..add (2)// 10
The first vertex in the code above is interpreted as the decimal point, and the second vertex is interpreted as the vertex operator. For the sake of semantic clarity, I will use parentheses.
The value returned by the add method can be chained.
Number.prototype.subtract = function (x) { return this - x;};(8) .add (2) .subtract (4)// 6
The above code deploys the subtract method on the instance of the Number object, which can be chained with the add method.
If you use square brackets to call properties, the writing method will be odd.
8["add"](2)["subtract"](4)// 6
We can also deploy more complex methods.
Number.prototype.iterate = function () { var result = []; for (var i = 0; i <= this; i++) { result.push (i); } return result;};(8) .iterate ()// [0, 1, 2, 3, 4, 5, 6, 7, 8]
The above code deploys the iterate method on the prototype of the Number object to automatically expand a value into an array.
In short, now we can directly call the method on the numeric value, but the back of a pair of parentheses looks a little inconspicuous. Is it possible to remove the parentheses? That is to say, can we convert the following expression
(8).double() .square ()
In another way?
(8).double.suqare
This can be done.
ES5 stipulates that each object's attribute has a value method get, which is used to customize the read operation of this attribute.
Number.prototype = Object.defineProperty ( Number.prototype, "double", { get: function (){return (this + this)} });Number.prototype = Object.defineProperty ( Number.prototype, "square", { get: function (){return (this * this)} });
The code above defines two properties double and square on Number. prototype, and their value method get.
Therefore, read the two attributes in any value and write them as follows.
(8).double.square// 256
You can also use the square brackets operator.
8["double"]["square"]// 256