如何在不是对象或功能的对象实例上进行原型制作?

时间:2019-05-22 01:09:36

标签: javascript function object prototype defineproperty

不建议扩展对象类,因此我尝试扩展对象,例如:

var obj = {'a': 1, 'b': 2, 'c': 3};

object literal {'a': 1, 'b': 2, 'c': 3}
new Object({'a': 1, 'b': 2, 'c': 3})相同。

我尝试了obj.prototype = {d: 4},但是它将'prototype'设置为属性,而不是真正的prototype
忘记Object.defineProperties
还尝试过Object.create:为什么这不起作用? ...

var ext = Object.create(obj, {'d': { value:4 }});
console.log(obj.isPrototypeOf(ext)) // => true! obj is prototype of ext
console.log(ext); // => {d: 4}
console.log(obj); // => {a: 1, b: 2, c: 3}

Console.log说obj.isPrototypeOf(ext) == true,为什么ext不是{'a': 1, 'b': 2, 'c': 3, 'd': 4}

如何在非Object类或Function的对象实例上原型化?

更新:由于尼古拉斯大厦的答案,我错过了the second parameter中的枚举,该数字应为:{'d': { value:4, enumerable: true }}

我在Chrome控制台中的箭头下拉菜单存在问题,我无法单击以查看继承的值。我本可以使用assign()来“扩展” obj 。现在它显示obj = {'a': 1, 'b': 2, 'c': 3} __proto__ {d: 4}没问题。从面向对象的角度来看,这意味着obj extends {d: 4} *。在对象obj上制作了原型。

我接受了来自 t.888 的回答,该回答帮助我了解了console.log如何显示对象以及扩展现有对象的正确方法。

2 个答案:

答案 0 :(得分:3)

  

为什么ext不是{'a':1,'b':2,'c':3,'d':4}吗?

是的,但是您没有使d能够枚举,因此console.log看不到它。

const obj = {'a': 1, 'b': 2, 'c': 3};
const ext = Object.create(obj, {'d': { 
  value:4, 
  enumerable: true // <---- added this
}});
console.log('ext', ext);
for (const key in ext) {
  if (ext.hasOwnProperty(key)) {
    console.log('own property', key, ext[key]);
  } else {
    console.log('inherited property', key, ext[key]);
  }
}

答案 1 :(得分:1)

您可以使用__proto__设置原型,但该原型被认为是旧功能:

const obj = {a: 1, b: 2, __proto__: { c: 3 }}
console.log(obj.c) // 3

更好的方法是使用Object.create扩展现有对象。定义函数很方便 为此:

/**
 * Extend an object by creating a new object with the given prototype.
 */
function extend(proto, obj) {
  // Create a new object with the given prototype
  const sub = Object.create(proto)

  if (obj) {
    // Copy the properties from 'obj' to the new object.
    Object.assign(sub, obj)
  }

  // Return the new object.
  return sub
}
// Define an object to serve as a prototype.
const proto = { a: 1, b: 2 }

// Create a new object with the given prototype.
const extended = extend(proto, { c: 3 })

console.log(extended.a, extended.b, extended.c) // 1 2 3

但是,正如另一个答案指出的那样,它实际上不会显示原型属性 在对象上

console.log(extended) // { c: 3 }

虽然存在,但它不在对象本身上,而在其原型上:

for (let key in extended) {
  console.log(key, extended[key])
}

输出:

c 3
a 1
b 2
console.log(extended.__proto__) // { a: 1, b: 2 }

Object.assign

如果您只想复制和/或合并对象,请使用Object.assign

const first = {a: 1}
const second = {b: 2}

// Put the properties from 'second' onto 'first'.
Object.assign(first, second) // first: {a: 1, b: 2}

// Copy 'first' and 'second' to a new object.
const third = Object.assign({c: 3}, first, second) // third: {c: 3, a: 1, b: 2}

这大致相当于手动复制属性:

const first = {a: 1}
const second = {b: 2}

for (let key in second) {
  if (second.hasOwnProperty(key)) {
    first[key] = second[key]
  }
}

console.log(first) // {a: 1, b: 2}

概括该代码,我们可以创建一个近似的Object.assignObject.assign可能不存在的older browsers

/**
 * Assign properties from object arguments [1..n] to the
 * zeroth object argument.
 */
function assign() {
  var first, rest

  // Check of Object.assign exists and use a fallback if it doesn't.
  if (typeof Object.assign === 'function') {
    // Copy each object's properties to the first one.
    return Object.assign.apply(null, arguments)
  } else {
    first = arguments[0]
    rest = Array.prototype.slice.call(arguments, 1)
    // Copy each object's properties to the first one.
    rest.forEach((obj) => {
      for (var key in obj) {
        // Don't copy any of obj's prototype's properties.
        if (obj.hasOwnProperty(key)) {
          first[key] = obj[key]
        }
      }
    })
    return first
  }
}
const obj = assign({c: 3}, {a: 1}, {b: 2})
console.log(obj) // {c: 3, a: 1, b: 2}
相关问题