【问题标题】:Change the class of a Javascript variable更改 Javascript 变量的类
【发布时间】:2021-05-01 15:21:48
【问题描述】:

是否可以更改 Javascript 变量的类?

假设我有 2 个课程:

class A {
  constructor(x) {
    this.x = x;
  }
}

class B {
  constructor(x, y) {
     this.x = x;
     this.y = y;
  }
}

还有一个A型变量

let a = new A(20);

我怎么能改变a的类型,这样

(a instanceof B)

返回真而不是假?

编辑:我想知道解决一个特定的问题。我有一个树结构,其中树的每个节点都是 A 类或 B 类的 Javascript 对象(实际上我有更多类都继承自基类,但让我们保持简单)。 在某些时候,我想将节点 A 转换为节点 B。但我只能访问节点本身,而不是父节点。所以我想在 A 类中创建一个方法,将实例化变量转换为 B 类的对象。

【问题讨论】:

  • 这是纯粹的好奇还是您要解决的具体问题? (在这种情况下,请告诉我们更多信息)。
  • 我正在尝试解决一个特定问题。我编辑了我的问题

标签: javascript class oop


【解决方案1】:

让其中一个类扩展另一个类?

class B {
  constructor(x, y) {
     this.x = x;
     this.y = y;
  }
}
class A extends B {
  constructor(x) {
    super();
    this.x = x;
  }
}



let a = new A(20);
console.log(a instanceof B);

或者手动设置原型,从A返回一个对象(奇怪):

class B {
  constructor(x, y) {
     this.x = x;
     this.y = y;
  }
}
class A {
  constructor(x) {
    const instance = Object.create(B.prototype);
    instance.x = x;
    return instance;
  }
}



let a = new A(20);
console.log(a instanceof B);

或者在外面做(非常奇怪,不要这样做):

class B {
  constructor(x, y) {
     this.x = x;
     this.y = y;
  }
}
class A {
  constructor(x) {
    this.x = x;
  }
}



let a = new A(20);
Object.setPrototypeOf(a, B.prototype);
console.log(a instanceof B);

【讨论】:

    【解决方案2】:

    为了响应您的更新,一种可能的解决方案是使用Pointer 对象。 Pointer 是一个透明代理,它将每个“设置”和“获取”操作重定向到其target。此外,它还提供了一个特殊属性(在此示例中为$$$),允许在不更改指针本身的情况下更改目标。这样,您可以“就地”替换对象,只需直接引用即可。

    对于应用程序的其余部分,Pointer(x) 的外观和行为与 x 完全相同。

    例子:

    let Pointer = target => new Proxy({}, {
        getPrototypeOf() {
            return Reflect.getPrototypeOf(target)
        },
        get(_, p) {
            return Reflect.get(target, p)
        },
        set(_, p, v) {
            if (p === '$$$')
                return target = v
            return Reflect.set(target, p, v)
        }
    })
    
    //
    
    class A {
        hello() {
            return 'aaa'
        }
    }
    
    class B {
        hello() {
            return 'BBB'
        }
    }
    
    let objects = [
        Pointer(new A),
        Pointer(new A),
        Pointer(new A),
        Pointer(new A),
    ]
    
    function setObjectToB(obj) {
        obj.$$$ = new B
    }
    
    console.log(...objects.map(x => x.hello()))
    console.log(objects[2] instanceof A)
    
    setObjectToB(objects[2])
    
    console.log(...objects.map(x => x.hello()))
    console.log(objects[2] instanceof B)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-28
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 2013-03-25
      • 2015-01-21
      • 2022-01-03
      相关资源
      最近更新 更多