Javascript中面向对象的方法

时间:2012-10-07 10:08:57

标签: node.js

是否可以在Java Script中使用 OO方法? 我在服务器端和客户端使用JavaScript 使用node.js.Currently我使用查询到CRUD操作而不是查询是否可以使用 DTO'S 来保存数据数据库?

1 个答案:

答案 0 :(得分:0)

是的,您可以使用原型继承来模拟它。规则是完全不同的,因为语言是原型驱动的,你需要做一些关于原型链等的研究,但最终它变得非常有用。

查看继承自EventEmitter的Node核心中的内容。它们有一个名为util.inherits的内置函数,它具有ECMA更高版本的实现。它看起来像这样:

/**
 * Inherit the prototype methods from one constructor into another.
 *
 * The Function.prototype.inherits from lang.js rewritten as a standalone
 * function (not on Function.prototype). NOTE: If this file is to be loaded
 * during bootstrapping this function needs to be rewritten using some native
 * functions as prototype setup using normal JavaScript does not work as
 * expected during bootstrapping (see mirror.js in r114903).
 *
 * @param {function} ctor Constructor function which needs to inherit the
 *     prototype.
 * @param {function} superCtor Constructor function to inherit prototype from.
 */
exports.inherits = function(ctor, superCtor) {
  ctor.super_ = superCtor;
  ctor.prototype = Object.create(superCtor.prototype, {
    constructor: {
      value: ctor,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
};

示例用法是Stream类:

https://github.com/joyent/node/blob/master/lib/stream.js#L22-29

var events = require('events');
var util = require('util');

function Stream() {
  events.EventEmitter.call(this);
}
util.inherits(Stream, events.EventEmitter);

在coffeescript中,类编译为稍微不同的代码集,归结为此__extends函数。我相信这将有更多的跨浏览器兼容性,但我没有特别回忆谁不支持Object.create。

var __hasProp = Object.prototype.hasOwnProperty, __extends = 
function(child, parent) { 
    for (var key in parent) { if (__hasProp.call(parent, key)) 
child[key] = parent[key]; } 
    function ctor() { this.constructor = child; } 
    ctor.prototype = parent.prototype; 
    child.prototype = new ctor; 
    child.__super__ = parent.prototype; 
    return child; 
  };