Search code examples
javascriptfunctionprototype

Array Prototype


I am trying to change the code so that the tests ("if condition (both)) returns true

function X(x) {
  this.x = x;
}

function Y(y) {
  this.y = y;
}

var x = new X(1);
var y = new Y("abc")

if (y instanceof X)
  console.log("true");

if (x instanceof Y)
  console.log("true");

This is what I tried so far ,But I am not getting correct result.

function X(x) {
  this.x = x;
}

function Y(y) {
  this.y = y;
}

X.prototype = Object.create(Y.prototype);
X.constructor = X;

var x = new X(1);
var y = new Y("abc");

if (y instanceof X)
  console.log("true");
if (x instanceof Y)
  console.log("true");

I am able to change only one object variable .not both.I am trying to both the result to return true.


Solution

  • As i said before, the only way is to trick out instanceof:

    function A(){
       return Object.create(B.prototype);
    }
    
    function B(){
       return Object.create(A.prototype);
    }
    

    That way you have cross inheritance, so all elements created with A inherit from B, and vice versa. Try it