创建自定义对象文字

时间:2015-08-21 19:48:24

标签: javascript object prototype instance

我正在寻找一种创建自定义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

3 个答案:

答案 0 :(得分:0)

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

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)

答案 1 :(得分:0)

  

这个答案是对的。我将它保留在这里,因为这些评论可能有助于理解这个问题。

所有表达式求值为true的原因是instanceof在左侧实例原型链中搜索右侧构造函数的原型(“type”)。 Object的原型和CustomObj的原型是相同的,因此在所有情况下表达式的计算结果为真

答案 2 :(得分:0)

function Custom (literal) {
  if (literal) return literal
  return {}
}
Custom.prototype = Object.prototype
Custom.prototype.constructor = Custom

var foo = new Custom()

if (foo.constructor.name === 'Custom') {
  // foo is a custom object literal
}

// However it registers as an instance of both `Custom` and `Object`
console.log(foo instanceof Custom) // => true
console.log(foo instanceof Object) // => true
console.log({} instanceof Custom) // => true
console.log({} instanceof Object) // => true