我正在寻找一种创建自定义 Object()
对象的方法。我想要一种方法来检查给定对象是什么的实例。我需要一种将自定义对象与 native 对象区分开来的方法。
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
。
最佳答案
我相信这可以满足您的要求。请注意,需要在使用此解决方案的构造函数中定义原型(prototype)的属性,因为原型(prototype)将被覆盖。
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/