如何使用原型继承来重写JS的getter &setter函数?

问题描述 投票:0回答:1

需要知道如何使用原型继承扩展覆盖getter和setter。

以下是一个例子来了解这个问题

function A() {
    this._loading = "Welcome";
}

Object.defineProperty(A.prototype, 'loading', {
    get() {
        return this._loading+" from A";
    },
    set(value) {
        this._loading = value;
    }
});

function B() {}
Object.defineProperty(B.prototype, 'loading', {
    get() {
        return this._loading+" from B";
    },
    set(value) {
        this._loading = value;
    }
});

var a=new A();
var b=new B();

b.__proto__=a; // Not sure if this is wrong. This assigns the whole prototype of A to B so that B is submerged

我的预期结果是b.loading应该返回给我。来自B的欢迎

相反,它的返回 欢迎来自A

希望得到帮助。

javascript object inheritance prototype getter-setter
1个回答
0
投票

欢迎来到stackoverflow ;)

在Javascript中,你有不同的方法来处理 "继承"。原生 改派。

1. 覆盖原型 通常情况下 视为陋习 访问原型,使用 __proto__. 在你的情况下,你是将B的整个原型重新分配,所以它只会替换所有的原型。

// Here you are overriding the prototype of "b"
b.__proto__=a;

// It refers to the prototype of a, so it the equivalent of calling a.loading
b.loading

2. 从其他原型继承--ES5。

function B() {
  // Call the constructor of A giving the "B.this" context
  A.call(this)
}
// Inherits from prototype of A
B.prototype = Object.create(A.prototype)
Object.defineProperty(B.prototype, 'loading', {
    get() {
        return this._loading+" from B";
    }
});

// You won't need to instanciate A to inherits from it
const b = new B();
b.loading // "Welcome from B"

3. 更进一步 在实际场景中,你可能希望从A中继承一些属性,并覆盖B中的其他属性,因为B继承了A,所以你可以从B.prototype和A.prototype中调用两个方法。

function A() {
  this._loading = "Welcome";
}

Object.defineProperty(A.prototype, "loadingA", {
    get: function loading() {
        return this._loading + " from A"
    }
});

Object.defineProperty(A.prototype, "loading", {
    get: function loading() {
        return this._loading + " from A"
    }
});


function B() {
  A.call(this)
}
B.prototype = Object.create(A.prototype)
Object.defineProperty(B.prototype, 'loading', {
    get() {
        return this._loading+" from B";
    }
});

var b = new B()
b.loading // Welcome from B
b.loadingA // Welcome from A

4. 再进一步--ES6+ 您可能想使用ES6类语法糖,它不那么啰嗦,也更容易理解。)

class A {
  constructor() {
    this._loading = "Welcome"
  }

  get loading() {
    return this._loading + " from A"
  }
}

class B extends A {
  get loading() {
    return this._loading + " from B"
  }
}

b.loading // Welcome from B
b.loadingA // Welcome from A

关于javascript继承的进一步阅读

© www.soinside.com 2019 - 2024. All rights reserved.