JavaScript 有多灵活?

2020-06-22

Ann Ann

首先,在 Number.prototype 对象上,部署一个 add 方法。

Number.prototype.add = function (x) {
  return this + x;
};

上面代码为 Number 对象实例定义了一个 add 方法。如果你对这种写法不熟悉,建议先阅读我写的《JavaScript 面向对象编程》

由于 Number 对象的实例就是数值,在数值上调用某个方法,数值会自动转为 Number 的实例对象,所以就得到了下面的结果。

8['add'](2)
// 10

上面代码中,调用方法之所以写成8['add'],而不是8.add,是因为数值后面的点,会被解释为小数点,而不是点运算符。

将数值放在圆括号中,就可以使用点运算符调用方法了。

(8).add(2)
// 10

其实,还有另一种写法。

8..add(2)
// 10

上面代码的第一个点解释为小数点,第二个点解释为点运算符。为了语义清晰起见,下面我统一采用圆括号的写法。

由于add方法返回的还是数值,所以可以链式运算。

Number.prototype.subtract = function (x) {
  return this - x;
};

(8).add(2).subtract(4)
// 6

上面代码在Number对象的实例上部署了subtract方法,它可以与add方法链式调用。

我们还可以部署更复杂的方法。

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]

上面代码在 Number 对象的原型上部署了 iterate 方法,可以将一个数值自动扩展为一个数组。

总之,现在我们可以在数值上直接调用方法了,但是后面一对圆括号看着有点碍眼,有没有可能去掉圆括号呢?也就是说,能不能将下面的表达式

(8).double().square()

写成另一种样子?

(8).double.suqare

这是可以做到的。

ES5规定,每个对象的属性都有一个取值方法get,用来自定义该属性的读取操作。

Number.prototype = Object.defineProperty(
  Number.prototype, "double", {
    get: function (){return (this + this)} 
  }
);

Number.prototype =  Object.defineProperty(
  Number.prototype, "square", {
    get: function (){return (this * this)} 
  }
);

上面代码在 Number.prototype 上定义了两个属性 double 和 square ,以及它们的取值方法 get 。

因此,在任一数值上,读取这两个属性,就可以写成下面的样子。

(8).double.square
// 256

也可以改用方括号运算符。

8["double"]["square"]
// 256
近期开课hot

Python零基础入门

start2025/02/12 03:14 (Sydney)

Web全栈班24期 NodeJS方向

start2024/12/08 11:30 (Sydney)

logo

Follow Us

linkedinfacebooktwitterinstagramweiboyoutubebilibilitiktokxigua

We Accept

/image/layout/pay-paypal.png/image/layout/pay-visa.png/image/layout/pay-master-card.png/image/layout/pay-stripe.png/image/layout/pay-alipay.png

地址

Level 10b, 144 Edward Street, Brisbane CBD(Headquarter)
Level 2, 171 La Trobe St, Melbourne VIC 3000
四川省成都市武侯区桂溪街道天府大道中段500号D5东方希望天祥广场B座45A13号
Business Hub, 155 Waymouth St, Adelaide SA 5000

Disclaimer

footer-disclaimerfooter-disclaimer

JR Academy acknowledges Traditional Owners of Country throughout Australia and recognises the continuing connection to lands, waters and communities. We pay our respect to Aboriginal and Torres Strait Islander cultures; and to Elders past and present. Aboriginal and Torres Strait Islander peoples should be aware that this website may contain images or names of people who have since passed away.

匠人学院网站上的所有内容,包括课程材料、徽标和匠人学院网站上提供的信息,均受澳大利亚政府知识产权法的保护。严禁未经授权使用、销售、分发、复制或修改。违规行为可能会导致法律诉讼。通过访问我们的网站,您同意尊重我们的知识产权。 JR Academy Pty Ltd 保留所有权利,包括专利、商标和版权。任何侵权行为都将受到法律追究。查看用户协议

© 2017-2024 JR Academy Pty Ltd. All rights reserved.

ABN 26621887572