简体   繁体   English

从 JavaScript 继承功能

[英]Inheriting functions from JavaScript

const startGame = {
 time : 0,
 start : function(){

 }
 next : function(){
 
 }

 end : function(){

 }
}


const anotherGame = { //want to inherit from startGame
 startAnother : function(){} //want to inherit from startGame.start
}

Given an object like this, I would like to inherit from it and give it a new property.给定一个这样的 object,我想继承它并赋予它一个新的属性。 For example, anotherGame extends startGame and takes all other properties, but I want to write additional code in addition to the properties of start function of startGame except for anotherStart function. What should I do?比如anotherGame扩展startGame ,取了其他所有的属性,但是我想在startGame的start function的属性之外再写一些除了anotherStart startGame以外的代码,怎么办?

Under the hood, ES6 classes use prototype to achieve inheritance:在底层,ES6 类使用原型来实现 inheritance:

 const startGame = { time: 0, start: function () { console.log("works", this.time); }, next: function () {}, end: function () {}, }; const anotherGame = { //want to inherit from startGame startAnother: function () { this.start(); }, //want to inherit from startGame.start }; // Magic happens here Object.setPrototypeOf(anotherGame, startGame); anotherGame.startAnother();

Using ES6 classes:使用 ES6 类:

 class StartGame { time = 0; start() { console.log("works", this.time); } next() {} end() {} } class AnotherGame extends StartGame { startAnother() { this.start(); } } const anotherGame = new AnotherGame(); anotherGame.startAnother();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM