首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >NodeJS中的JavaScript OOP :如何实现?

NodeJS中的JavaScript OOP :如何实现?
EN

Stack Overflow用户
提问于 2013-08-12 21:20:54
回答 6查看 149K关注 0票数 122

我习惯了Java中的经典OOP。

使用NodeJS在JavaScript中进行OOP的最佳实践是什么?

每个类都是一个包含module.export的文件

如何创建类?

this.Class = function() {
    //constructor?
    var privateField = ""
    this.publicField = ""
    var privateMethod = function() {}
    this.publicMethod = function() {} 
}

vs. (我甚至不确定它是否正确)

this.Class = {
    privateField: ""
    , privateMethod: function() {}

    , return {
        publicField: ""
        publicMethod: function() {}
    }
}

this.Class = function() {}

this.Class.prototype.method = function(){}

...

继承是如何工作的?

在NodeJS中是否有用于实现OOP的特定模块?

我正在寻找上千种不同的方法来创建类似OOP的东西。但是我不知道什么是最常用/实用/干净的方法。

奖励问题:建议与MongooseJS一起使用的"OOP风格“是什么?(可以将MongooseJS文档视为类和用作实例的模型吗?)

编辑

这是一个用JsFiddle编写的例子,请提供反馈。

//http://javascriptissexy.com/oop-in-javascript-what-you-need-to-know/
function inheritPrototype(childObject, parentObject) {
    var copyOfParent = Object.create(parentObject.prototype)
    copyOfParent.constructor = childObject
    childObject.prototype = copyOfParent
}

//example
function Canvas (id) {
    this.id = id
    this.shapes = {} //instead of array?
    console.log("Canvas constructor called "+id)
}
Canvas.prototype = {
    constructor: Canvas
    , getId: function() {
        return this.id
    }
    , getShape: function(shapeId) {
        return this.shapes[shapeId]
    }
    , getShapes: function() {
        return this.shapes
    }
    , addShape: function (shape)  {
        this.shapes[shape.getId()] = shape
    }
    , removeShape: function (shapeId)  {
        var shape = this.shapes[shapeId]
        if (shape)
            delete this.shapes[shapeId]
        return shape
    }
}

function Shape(id) {
    this.id = id
    this.size = { width: 0, height: 0 }
    console.log("Shape constructor called "+id)
}
Shape.prototype = {
    constructor: Shape
    , getId: function() {
        return this.id
    }
    , getSize: function() {
        return this.size
    }
    , setSize: function (size)  {
        this.size = size
    }
}

//inheritance
function Square(id, otherSuff) {
    Shape.call(this, id) //same as Shape.prototype.constructor.apply( this, arguments ); ?
    this.stuff = otherSuff
    console.log("Square constructor called "+id)
}
inheritPrototype(Square, Shape)
Square.prototype.getSize = function() { //override
    return this.size.width
}

function ComplexShape(id) {
    Shape.call(this, id)
    this.frame = null
    console.log("ComplexShape constructor called "+id)
}
inheritPrototype(ComplexShape, Shape)
ComplexShape.prototype.getFrame = function() {
    return this.frame
}
ComplexShape.prototype.setFrame = function(frame) {
    this.frame = frame
}

function Frame(id) {
    this.id = id
    this.length = 0
}
Frame.prototype = {
    constructor: Frame
    , getId: function() {
        return this.id
    }
    , getLength: function() {
        return this.length
    }
    , setLength: function (length)  {
        this.length = length
    }
}

/////run
var aCanvas = new Canvas("c1")
var anotherCanvas = new Canvas("c2")
console.log("aCanvas: "+ aCanvas.getId())

var aSquare = new Square("s1", {})
aSquare.setSize({ width: 100, height: 100})
console.log("square overridden size: "+aSquare.getSize())

var aComplexShape = new ComplexShape("supercomplex")
var aFrame = new Frame("f1")
aComplexShape.setFrame(aFrame)
console.log(aComplexShape.getFrame())

aCanvas.addShape(aSquare)
aCanvas.addShape(aComplexShape)
console.log("Shapes in aCanvas: "+Object.keys(aCanvas.getShapes()).length)

anotherCanvas.addShape(aCanvas.removeShape("supercomplex"))
console.log("Shapes in aCanvas: "+Object.keys(aCanvas.getShapes()).length)
console.log("Shapes in anotherCanvas: "+Object.keys(anotherCanvas.getShapes()).length)

console.log(aSquare instanceof Shape)
console.log(aComplexShape instanceof Shape)
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2013-08-12 21:26:41

这是一个开箱即用的例子。如果你想要少一些"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;
票数 119
EN

Stack Overflow用户

发布于 2016-01-18 11:57:37

作为Node.js社区,确保来自JavaScript ECMA-262规范的新功能及时带给Node.js开发人员。

您可以查看JavaScript classes。在JavaScript6的Javascript类中引入了MDN link to JS classes ,这种方法提供了在JavaScript中建模OOP概念的更简单的方法。

注意::JS类只能在严格模式中工作。

下面是一些用Node.js (使用Node.js Version v5.0.0 )编写的类和继承的框架。

类声明:

'use strict'; 
class Animal{

 constructor(name){
    this.name = name ;
 }

 print(){
    console.log('Name is :'+ this.name);
 }
}

var a1 = new Animal('Dog');

继承:

'use strict';
class Base{

 constructor(){
 }
 // methods definitions go here
}

class Child extends Base{
 // methods definitions go here
 print(){ 
 }
}

var childObj = new Child();
票数 47
EN

Stack Overflow用户

发布于 2013-08-12 21:30:05

我建议使用标准util模块附带的inherits助手:http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor

下面是一个如何在链接页面上使用它的示例。

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18188083

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档