Mut*_*han 8 javascript inheritance
从OOPS基础开始,我总是使用继承作为代码重用的强大工具,
例如,如果我在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.
};
Run Code Online (Sandbox Code Playgroud)
我可以用has-ajavascript中的关系做到这一点,但我看到的缺点是,我必须重新定义派生类中的每个函数.
示例:在每个车,骑士,典当,国王......等中再次重新定义getTeamColor().
var Pawn = function(teamColor,pos){
var piece = new Piece(teamColor,pos);
.......
this.getTeamColor = function(){
return piece.getTeamColor();
};
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,为什么javascript不支持经典继承作为默认选项?
Pet*_*tai 17
[2018年更新]现在,JavaScript显然支持使用本机语言功能进行继承.
class A { }
class B extends A { }
Run Code Online (Sandbox Code Playgroud)
[/更新]
JavaScript确实支持原型方式的继承.你需要的不是类,而是行为的封装和覆盖的能力.
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"); }
Run Code Online (Sandbox Code Playgroud)
现在:
var p = new Pawn(); p.color = "black";
> p instanceof Piece
Run Code Online (Sandbox Code Playgroud)
真正
p instanceof Pawn
Run Code Online (Sandbox Code Playgroud)
真正
p.getColor()
Run Code Online (Sandbox Code Playgroud)
"黑色"
p.move()
Run Code Online (Sandbox Code Playgroud)
警报...
这是基本的方法,并且有许多库将这变成了对于想要课程的人来说熟悉的东西 - 所以说.
例如,使用JayData,您可以以更加封装的方式编写前一个(在链上自动构造函数调用的奖励:
var Piece = $data.Base.extend("Piece", {
move: function() { throw "pure class" }
});
var Pawn = Piece.extend("Pawn", {
move: function() { ... }
});
var p = new Pawn();
Run Code Online (Sandbox Code Playgroud)