gpt4 book ai didi

javascript - 从 super 继承属性

转载 作者:行者123 更新时间:2023-11-30 14:21:55 24 4
gpt4 key购买 nike

我是 JS 的新手 - 和许多 JS 初学者一样,我对属性继承有些困惑。据我了解,构造函数拥有一个名为原型(prototype)的属性。此属性指向一个原型(prototype)对象。所以当我定义两个构造函数时:

function Super(){
this.x = 1 }

function Sub(){
this.y = 2 }

它们都指向一个原型(prototype)对象。

通过下面这行代码,Sub 将继承 Super 的属性:

Sub.prototype = new Super();

现在的问题是:这里到底发生了什么? Sub.prototype 指向的“旧”原型(prototype)对象是否会被使用 new Super() 创建的新对象替换?

亲切的问候亨宁

最佳答案

是的,在某种程度上

function Super(){
this.x = Math.random()
}

function Sub(){
this.y = 2 //this will be keeped
}
Sub.prototype.myMethod = function(){} //this will be lost

Sub.prototype = new Super();

但是通过这种方式你依赖单例

console.log(new Sub().x === new Sub().x) //true

如果你想完成覆盖原型(prototype),你可以这样做

Sub.prototype = Super.prototype

如果你想扩展覆盖原型(prototype),你可以这样做

Object.assign(Sub.prototype, Super.prototype)

如果你想扩展原型(prototype),你可以这样做

Object.assign(Sub.prototype, {...Super.prototype, ...Sub.prototype})

或者在现代 ES6 中

class Sub extends Super{
constructor(){
super()
//...
}
}

关于javascript - 从 super 继承属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52613326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com