user985399
user985399

Reputation:

How to prototype on object instance that is not Object or Function?

Extending Object class is not recommended, so I try to extend an object, for example:

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

Here the object literal {'a': 1, 'b': 2, 'c': 3}
is same as new Object({'a': 1, 'b': 2, 'c': 3}).

I tried obj.prototype = {d: 4} but it set 'prototype' as property, not a real prototype.
Forget Object.defineProperties!
Also tried Object.create: Why does this not work? ...

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 say obj.isPrototypeOf(ext) == true so why is ext not {'a': 1, 'b': 2, 'c': 3, 'd': 4} ?

How to prototype on object instance that is not Object class or Function?

Update: As Nicholas Tower answer i have missed enumerable in the second parameter that should be: {'d': { value:4, enumerable: true }}

I had issue with arrow-dropdown in Chrome console that I missed to click to see the inherited values. I could have used assign() to "extend" obj. Now it show obj = {'a': 1, 'b': 2, 'c': 3} __proto__ {d: 4} that is ok. From OO view that means obj extends {d: 4}*. Made a prototype on the object obj.

I accepted answer from t.888 that helped me see how console.log show objects and the correct way to extend an existing object.

Upvotes: 1

Views: 102

Answers (2)

t.888
t.888

Reputation: 3902

You can use __proto__ to set a prototype but its considered a legacy feature:

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

A better way is to extend an existing object with Object.create. It's convenient to define a function for this purpose:

/**
 * 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

However as another answer pointed out, it won't show the prototype properties actually on the object:

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

It's there though, it's just not on the object itself but on its prototype:

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

Output:

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

Object.assign

If you just want to copy and/or combine objects, use 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}

This is roughly equivalent to copying properties manually:

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}

Generalizing that code, we can create an approximation of Object.assign that works on older browsers where Object.assign may not present:

/**
 * 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}

Upvotes: 0

Nicholas Tower
Nicholas Tower

Reputation: 85211

why is ext not {'a': 1, 'b': 2, 'c': 3, 'd': 4} ?

It is, but you didn't make that d enumerable, so console.log doesn't see it.

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]);
  }
}

Upvotes: 2

Related Questions