由于直接扩展内置对象是不好的做法,我正在考虑创建一个扩展全局对象的本地对象,例如使用 $.extend(obj, Math)
。 Math
是一个对象,但是您似乎无法像这样访问它的任何属性:
for (obj in Math) {
console.log(obj);
}
为什么?
最佳答案
因为它们都被定义为不可枚举。规范定义对象的几乎所有内置属性都是不可枚举的。当您枚举对象中的属性时(通过 for-in
或 Object.keys
),不可枚举的属性不会显示。
不过,有两个想法:
您可以使用
Math
作为其原型(prototype)来创建您的对象,如下所示:// Create the MyMath object with Math as its prototype var MyMath = Object.create(Math); // Check that MyMath has a Math function on it display(MyMath.floor(2.3)); // Utility function function display(msg) { document.body.insertAdjacentHTML("beforeend", "<p>" + msg + "</p>"); }
ES5 引入了一个新函数,
Object.getOwnPropertyNames
,它可以从对象中获取所有属性(可枚举和不可枚举)的名称。 (由于Math
的原型(prototype)是Object.prototype
,您可能只需要“自己的”属性。)所以您可以在符合 ES5 的引擎上执行此操作:// Create the MyMath object with all of the own properties on Math var MyMath = {}; Object.getOwnPropertyNames(Math).forEach(function(name) { MyMath[name] = Math[name]; }); // Check that MyMath has a Math function on it display(MyMath.floor(2.3)); // Utility function function display(msg) { document.body.insertAdjacentHTML("beforeend", "<p>" + msg + "</p>"); }
选项 1 可能是您更好的选择,尤其是因为 Object.create
的单参数版本可以在 ES5 之前的引擎上填充/填充。
关于javascript - 在 JavaScript 中扩展 Math 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26296097/