栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

NodeJS中的JavaScript OOP:如何?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

NodeJS中的JavaScript OOP:如何?

这是一个开箱即用的示例。如果您想减少“ hacky”,则应使用继承库或类似的库。

在文件animal.js中,您应该编写:

var method = Animal.prototype;function Animal(age) {    this._age = age;}method.getAge = function() {    return this._age;};module.exports = Animal;

要在其他文件中使用它:

var Animal = require("./animal.js");var john = new Animal(3);

如果要“子类”,请在mouse.js中:

var _super = require("./animal.js").prototype,    method = Mouse.prototype = Object.create( _super );method.constructor = Mouse;function Mouse() {    _super.constructor.apply( this, arguments );}//Pointless override to show super calls//note that for performance (e.g. inlining the below is impossible)//you should do//method.$getAge = _super.getAge;//and then use this.$getAge() instead of super()method.getAge = function() {    return _super.getAge.call(this);};module.exports = Mouse;

您也可以考虑“方法借用”而不是垂直继承。您无需从“类”继承即可在其类上使用其方法。例如:

 var method = List.prototype; function List() { } method.add = Array.prototype.push; ... var a = new List(); a.add(3); console.log(a[0]) //3;


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/485078.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号