【发布时间】:2015-11-15 20:47:32
【问题描述】:
我正在寻找一种方法来创建自定义 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)
我假设这是因为我从 Object 继承了 prototypes。我尝试添加一个this.name,但它并没有改变instanceof。
【问题讨论】:
-
“我尝试添加
this.name” 那么,您向对象添加了name属性,您希望更改什么? -
@blex 我预计
custom.constructor.name会发生变化,并且instanceOf会使用该名称来检测对象是instanceOf。 -
JavaScript 中的对象总是要继承自 Object。
-
@Adam 好的,这如何帮助我实现我想要做的事情?
-
@Adam -
Object.create(null)
标签: javascript object prototype instance