2012-10-07 26 views
3

在Java腳本中是否可以使用OO方法? 我使用JavaScript在服務器端和客戶端使用node.js.Currently我使用查詢到CRUD操作,而不是查詢是否可以使用DTO'S保存數據庫中的數據?Java腳本中面向對象的方法

+0

請閱讀道格拉斯Crockford的*的JavaScript:好的部分」 – ebohlman

+0

OK ebohiman我會嘗試 – Baskar

回答

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; 
    }; 
+0

OK喬什我會嘗試。 – Baskar