我正在寻找一种创建自定义Object()对象的方法。我想要一种检查给定对象是什么实例的方法。我需要一种将自定义对象与本机对象区分开的方法。

function CustomObj (data) {
  if (data) return data
  return {}
}
CustomObj.prototype = Object.prototype

var custom = new CustomObj()
var content = new CustomObj({'hello', 'world'})
var normal = new Object()

console.log(custom) // => {}
console.log(content) // => {'hello', 'world'}
console.log(custom instanceof CustomObj) // => true (expected: true)
console.log(content instanceof CustomObj) // => true (expected: true)
console.log(custom instanceof Object) // => true (expected: false)
console.log(content instanceof Object) // => true (expected: false)
console.log(normal instanceof CustomObj) // => true (expected: false)
console.log(normal instanceof Object) // => true (expected: true)


我假设这是因为我要从prototypes继承Object。我尝试添加this.name,但它没有更改instanceof

最佳答案

我相信这可以满足您的要求。注意,需要使用此解决方案在构造函数中定义原型的属性,因为原型将被覆盖。

function CustomObj (data) {
  CustomObj.prototype = Object.create(null)
  CustomObj.prototype.x = "Hello world!"

  return Object.create(CustomObj.prototype)
}

var custom = new CustomObj()
var normal = new Object()

console.log(custom.x); // => "Hello world!" (expected: "Hello world!")
console.log(custom instanceof CustomObj) // => true (expected: true)
console.log(custom instanceof Object) // => false (expected: false)
console.log(normal instanceof CustomObj) // => false (expected: false)
console.log(normal instanceof Object) // => true (expected: true)

关于javascript - 创建自定义对象文字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32148244/

10-12 12:46
查看更多