javascript - 创建自定义对象文字

标签 javascript object prototype instance

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

相关文章:

javascript - 如何在选择标签中添加虚线作为选项?

javascript - 以编程方式在jstree中添加节点

javascript - 如何在 JavaScript 中获取随机选择对象的键?

java - 从 Jlist 获取对象的实例

java - 为什么使用 ImageIcon 而不是 Image?

javascript - React Native 将 http 图像保存到 Android 相机胶卷

java - 如何检测 JComboBox 中选定的对象?

javascript - Location 对象的原型(prototype)对象是什么?

javascript - JS 继承和变异原型(prototype)

javascript - new 关键字在幕后做了什么?