gpt4 book ai didi

javascript - 为什么 Javascript 默认不支持继承?

转载 作者:数据小太阳 更新时间:2023-10-29 03:59:48 25 4
gpt4 key购买 nike

从 OOPS base 开始,我一直使用继承作为代码重用的强大工具,

例如,如果我用 OOPS 编写一个国际象棋程序,并且当我实现一个 is-a 关系时,

Class Piece{
int teamColor;
bool isLive;
Positon pos;
int Points;
.......
int getTeamColor(){....}
.......
};

Class Rook extend Piece{ //`is-a`
...... // No getTeamColor() definition here.. because the parent has the definition.
};

Class Pawn extend Piece{ //`is-a`
......// No getTeamColor() definition here.. because the parent has the definition.
};

我可以用 javascript 中的 has-a 关系来做到这一点,但我看到的缺点是,我也必须重新定义派生类中的每个函数。

示例:在每个 rook、knight、pawn、king.... 等中再次重新定义 getTeamColor()

     var Pawn = function(teamColor,pos){
var piece = new Piece(teamColor,pos);
.......

this.getTeamColor = function(){
return piece.getTeamColor();
};
}

我的问题是,为什么 javascript 不支持经典继承作为默认选项?

最佳答案

[2018年更新]JavaScript 现在显然支持具有本地语言特性的继承。

class A { }
class B extends A { }

[/更新]

JavaScript 确实支持原型(prototype)方式的继承。这里需要的不是类,而是行为的封装和覆盖的能力。

function Piece() { }

Piece.prototype.color = "white";
Piece.prototype.getColor = function() { return this.color }
Piece.prototype.move = function() { throw "pure function" };

function Pawn() { }
Pawn.prototype = new Piece();
Pawn.prototype.move = function() { alert("moved"); }

现在:

var p = new Pawn(); p.color = "black";

> p instanceof Piece

正确

 p instanceof Pawn

正确

p.getColor()

“黑色”

p.move()

提醒...

这是基本方法,有许多库可以将其转化为想要类的人所熟悉的东西 - 可以这么说。

例如,使用 JayData,您可以以更加封装的方式编写前一个(具有在链上自动调用构造函数的好处:

var Piece = $data.Base.extend("Piece", {
move: function() { throw "pure class" }
});

var Pawn = Piece.extend("Pawn", {
move: function() { ... }
});

var p = new Pawn();

关于javascript - 为什么 Javascript 默认不支持继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16261044/

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