【问题标题】:Can you set the internal [[Class]] property of an ECMAScript object?您可以设置 ECMAScript 对象的内部 [[Class]] 属性吗?
【发布时间】:2012-01-30 03:04:08
【问题描述】:

你能设置一个ECMAScript对象的the internal [[Class]] property吗?

【问题讨论】:

  • 请注意,内部的 [[Class]] 属性将在 ES6 中被移除。
  • @Raynos 有趣。那么Array.isArray() 和类似的函数将如何工作呢?
  • 不确定,他们会使用一些合理的检测,可能是Array.protototype.isPrototypeOf(someArray);
  • @JoshSmith function isArray(x) { return [].concat(x)[0] !== x; } ;)

标签: javascript


【解决方案1】:

你无法欺骗体面的 javascript 引擎。

你可以用

欺骗用户登陆代码
x.toString = function () {
  return '[object Array]';
}

【讨论】:

  • 这不适用于Object.prototype.toString.call(object)
  • @xfix 总是可以覆盖Object#toString(尽管根本不推荐)
  • @minmaxavg 但是人们想要覆盖[[class]]的原因通常是因为他们想将它与Object.prototype.toString.call一起使用来获取对象的类型。
猜你喜欢
  • 2016-06-24
  • 2010-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-04
相关资源
最近更新 更多