繁体   English   中英

在JavaScript ES6中破坏对象的功能

[英]destructing object's function in JavaScript ES6

 const circle = { radius: 10, color: 'orange', getArea: function() { return Math.PI * this.radius * this.radius; }, getCircumference: function() { return 2 * Math.PI * this.radius; } }; let {radius, getArea, getCircumference} = circle; console.log(getArea()); 

我得到了半径值和颜色,但是当我调用getArea(1)或getArea(5)时,我得到了NaN,如何使函数起作用?

预计将获得314.15

对于正常的功能,价值this是由你如何调用一个函数来确定。 如果您致电:

circle.getArea()

然后就是说用this等于circle来调用getArea函数。 相反,如果您有一个独立的函数并调用

getArea()

然后,你没有带它说什么this应该平等的,所以它默认为window对象(在非严格模式下)或不确定的(严格模式)。 而是以第一种方式调用它,或使用call / apply显式设置this的值

getArea.call(circle)

或创建函数的绑定副本。

const boundGetArea = circle.getArea.bind(circle);
boundGetArea();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM