tonitone120
tonitone120

Reputation: 2320

Why is the result not what I expect?

I'm copying this code snippet into Chrome's console.

function F() {};
F.prototype.fMethod = function WOT() {console.log(this)};

function G() {};

Object.setPrototypeOf(G.prototype, {...F.prototype.fMethod, ...Object.prototype})

console.log(Object.getPrototypeOf(G.prototype));

What I expected Object.getPrototypeOf(G.prototype) to return was

{
function WOT, //the content/properties of the object `F.prototype.fMethod` points to.
constructor: ... //the content/properties of the object Object.prototype points to. 
hasOwnProperty: ...
isPrototypeOf: ... 
}

You can see what I get on Chrome console here:

enter image description here

Upvotes: 1

Views: 115

Answers (2)

Alessandro Chitolina
Alessandro Chitolina

Reputation: 906

On the line

Object.setPrototypeOf(G.prototype, {...F.prototype.fMethod, ...Object.prototype})

You are setting the prototype of G.prototype as an empty object because

// You are unpacking two objects
{
  ...F.prototype.fMethod, // is your WOT function which has no owned properties to unpack
  ...Object.prototype // which is an empty object
}

Upvotes: 1

Daniele Ricci
Daniele Ricci

Reputation: 15837

Apart from it is not clear what you want to achieve, probably the most close we can be to what you want to achieve could be:

function F() {};
F.prototype.fMethod = function WOT() { console.log(this) };

function G() {};

console.log(Object.prototype);

Object.setPrototypeOf(G, { ...F.prototype,
  // since Object.prototype is an empty object, next line is irrelevant
  ...Object.prototype
});

console.log(Object.getPrototypeOf(G));

Once said that I strongly suggest you to clarify which is your target so we can help you to find a better way to achieve it.

Upvotes: 1

Related Questions