proto-scope
Writes objects without class
, but in the prototype way.
Usage
npm install --save proto-scope
Here is a demo of using it:
proto = require 'proto-scope'
- Inherent
Passing object to proto.as
to create sub-class,
passing object to proto.new
to create instance:
human = protoas : -> @name = 'human race' : : -> consolelog "this is " tom = humannewtomintroduce # => "this is human race" man = humanas : -> print 'speaks by'@namedan = mannewdangive_name 'Dan'danintroduce # => "this is Dan" danspeak # => "speaks by Dan"
- Super
a = protoas : -> consolelog 'this is a'b = aas : -> consolelog 'this is b' @superc = bnew : -> consolelog 'this is c' @super
Implementation
the difference between new
and as
is: new
contains @init?()
:
module.exports = : o = object or o.__proto__ = @ o : o = @as object oinit? o
Also, we my need super
, so dirty code comes:
module.exports = : o = object or o.__called__ = undefined o.__proto__ = @ for keyvalue of o = if typeof value is 'function' if key in 'as''new''super' return okey= o.__called__ = key valueapply oargs okeytoString = -> valuetoString f keyvalue o : -> @__proto__@__called__?
Read this for more details: http://javascript.info/tutorial/inheritance Also available for JavaScript if you like that kind of life style...
Limitations
This can not be widely used, since __proto__
is not supported in some platforms.
Actually there are some problems implementing OOP with prototype,
and more people choose using class
, but prototype is a simple concept.
Learn from Lua
This is kind of syntax from Lua: http://www.lua.org/pil/16.1.html
function Account:new (o) o = o or {} -- create object if user does not provide one setmetatable(o, self) self.__index = self return o end
License
MIT