Last active
December 14, 2015 20:19
-
-
Save szanata/5143421 to your computer and use it in GitHub Desktop.
JavaScript "class"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// naming a class | |
function Car(brand,model,powerOutput){ | |
var | |
_brand = brand, | |
_model = model, | |
_spec = powerOutput > 200 ? 'race' : 'street'; | |
Object.defineProperties(this,{ | |
brand:{ | |
get: function (){ return _brand}, | |
set: function (brand){ _brand = brand}, | |
enumerable: true | |
}, | |
model: { | |
get: function (){ return _model}, | |
set: function (model){ _model = model}, | |
enumerable:true | |
}, | |
spec: { | |
get: function (){ return _spec}, | |
enumerable:true | |
} | |
}); | |
Object.seal(this); | |
} | |
// make the Car class non overwritable | |
Object.defineProperty(window, 'Car', { value: Car, enumerable: true, writable:false }); | |
// inheritance | |
function FastCar(type){ | |
var | |
_type = type, | |
_racer; | |
Object.defineProperties(this, { | |
type: { | |
get: function () { return _type; }, | |
enumerable: true | |
}, | |
racer:{ | |
get: function (){ return _racer;}, | |
set: function (v){ _racer = v;}, | |
enumerable: true | |
} | |
}); | |
// call father (super); | |
Car.call(this,'Honda','Civic SI',202); | |
// make this object non extensible | |
Object.seal(this); | |
} | |
FastCar.prototype = Object.create(Car.prototype,{constructor:{value:FastCar}}); | |
Object.defineProperty(window, 'FastCar', { value: FastCar, enumerable: true, writable:false }); | |
//make some Singleton | |
var CarType = (function (){ | |
var types = Object.create(Object.prototype); | |
Object.defineProperties(types,{ | |
GT:{value:1}, | |
Prototype:{value:2}, | |
Dragster:{value:3}, | |
Monoposto:{value:4} | |
}); | |
return types; | |
})(); | |
Object.defineProperty(window, 'CarType', { value: CarType, enumerable: true, writable:false }); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment