Skip to content

Instantly share code, notes, and snippets.

@dmh2000
Created November 4, 2015 01:18
Show Gist options
  • Save dmh2000/9c0c2ef42f24de4bd4fd to your computer and use it in GitHub Desktop.
Save dmh2000/9c0c2ef42f24de4bd4fd to your computer and use it in GitHub Desktop.
javascript objects : create, clone, get/set
"use strict";
var util = require('util');
var clone = require('clone');
function inspect(o) {
console.log(util.inspect(o));
}
function clone1(o) {
var n = {};
var d;
for(var p in o) {
if (o.hasOwnProperty(p)) {
d = Object.getOwnPropertyDescriptor(o, p);
Object.defineProperty(n, p, d);
}
}
return n;
}
// ES6 class
var X = class {
constructor(x) {
// data property
this._x = x;
// function
this.f = function() {
console.log('X::f');
};
};
// getter/setter
get x() { return this._x; }
set x(v) { this._x = v; }
};
// legacy object creation by constructor function
var Y = function(x) {
if (this instanceof Y) {
// data property
this._x = x;
// function
this.f = function() {
console.log('Y::f');
};
// getter/setter
Object.defineProperties(this, {
"x" : {
enumerable: true,
set: function(v) {this._x = v;},
get: function() {return this._x;}
}
}
);
}
else {
return new Y(x);
}
};
// object literal with getter/setter
var Z = {
// data property
_x : 1,
// function
f : function() {
console.log('Z::f');
},
// getter/setter
get x() {return this._x;},
set x(v) {this._x = v;}
};
// object literal without getters/setters
var Q = {
// data property
_x : 1,
// function
f : function() {
console.log('Q::f');
},
// getter/setter
x : function(v) {
if (v) {
this._x = v;
}
return this._x;
}
};
console.log('X');
var a = new X(1);
a.f();
inspect(a);
console.log('Y');
var b = new Y(1);
b.f();
inspect(b);
console.log('Z');
var c = Z;
c.f();
inspect(c);
console.log('clone');
var d = clone(b);
var e = clone1(b);
inspect(b);
inspect(d);
inspect(e);
console.log('Q');
var q = Q;
inspect(q);
q.f();
var r = clone(q);
inspect(r);
r.x(2);
inspect(r);
console.log(r.x());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment