How to reuse object constructor? - javascript

This is how I create objects from a hash of properties:
var object = new function (data) {
var self = this;
self.property = data.property;
self.anotherProperty = data.anotherProperty;
self.method = function () { return 'something'; }
self.update = function (newData) {
//what is here ?
//i could have written:
self.property = newData.property;
self.anotherProperty = newData.anotherProperty;
//but why not reuse the constructor?
}
};
I wonder how to reuse this function (constructor) to update an object from hash.
So that:
object.update(newData)
would update current object properties from newData hash the same way it is done in the constructor function.

By giving the constructor a name?
function MyNotReallyClass(data){
var self = this;
self.property = data.property;
self.method = function () { return 'something'; }
self.update = MyMyNotReallyClass;
};
you can can now call
var obj = new MyNotReallyClass(data);
var obj2 = new MyNotReallyClass(data);
and
obj.update(data);
i hope this helps.. i not 100% sure, because i'm learning too.. but yeah try it ;)
edit: after reading this comment of you: "But that would return a new instance, wouldn't it? Which i don't want."
i think you can write the Update function and call it in your constructor
var object = new function (data) {
var self = this;
self.update = function (newData) {
self.property = data.property;
self.method = function () { return 'something'; }
// and other things You want to do in constructor and update
}
self.update(data);
}
;

Related

How to define a local function in Constructor.prototype in Javascript

Hi Guys I am facing difficulty in one of scenario where in I m not able to define local function in my Manager.prototype. Please find below detail..
I have a Constructor Function Employee.
function Employee(id){
this.id = id;
}
Employee.prototype.getID = function(){
return this.id;
}
var mark = new Employee(123);
Again I have a Manager Constructor
function Manager(managerOf){
this.managerOf = managerOf;
}
Manager.prototype = Object.create(Employee.prototype);
Manager.prototype.getManagerOf = function(){
return this.managerOf;
}
var john = new Manager(mark);
Now I want to define a function calcSalary() which is only accessible from getManagerOf() method & not from outside. [john.calcSalary() should not work]
You could hide it with a self executing function.
var Manager = (function() {
function calcSalary() {}
function Manager(managerOf){
this.managerOf = managerOf;
}
Manager.prototype = Object.create(Employee.prototype);
Manager.prototype.getManagerOf = function(){
// call calcSalary
return this.managerOf;
}
return Manager;
}());
var john = new Manager(mark);

JS use get in constructor

In a "basic" object, it's easy to define a 'get' property.
var anObject = {
get aProperty() {
return "abc";
}
}
document.write(anObject.aProperty); //abc
I find a solution to add a get property in a constructor function.
var BasicConstructor = function ()
{
Object.defineProperty(this, "aProperty", {get : function(){ return "abc"; }});
}
var anOtherObject = new BasicConstructor ();
document.write(anOtherObject.aProperty); //abc
Is their a more simple and readable solution ? I try some solution like the one below without success.
var BasicConstructor = function ()
{
this.aProperty = get ()
{
return "abc";
}
}
var anOtherObject = new BasicConstructor ();
document.write(anOtherObject.aProperty); //abc
Since your question is tagged with ecmascript-6
You can just use es6 class syntax and a getter:
class BasicConstructor {
get aProperty() { return 'abc'; }
};
var anOtherObject = new BasicConstructor();
document.write(anOtherObject.aProperty); //abc
this.aproperty = get () {} is invalid syntax. you need the "function" keyword (and you don't really need the get at all, but you can keep it if you want)
var BasicConstructor = function ()
{
this.aProperty = function get ()
{
return "abc";
}
}
var anOtherObject = new BasicConstructor ();
document.write(anOtherObject.aProperty()); //abc

What the best way to keep track of a javascript object reference when prototyping

what's best practice when it comes to keeping track of an object reference in javascript:
function class1(param) {
this.param = param;
self = this;
}
class1.prototype.method1 = function () {
console.log(self.param);
}
$('document').ready(function () {
object1 = new class1('foo');
object2 = new class1('bar');
object1.method1(); // expected: foo , actual: bar
})
http://jsfiddle.net/d7q5f/
Currently self appears to be global and is overridden in the constructor of object2. I'd be very grateful if someone could offer some advice.
You don't need to keep track, just use this like so:
function class1(param) {
this.param = param;
}
class1.prototype.method1 = function () {
console.log(this.param);
}
function class1(param) {
this.param = param;
}
class1.prototype.method1 = function () {
console.log(this.param);
}
$('document').ready(function () {
var object1 = new class1('foo');
var object2 = new class1('bar');
object1.method1(); // expected: foo , actual: foo
});
Why you want to add this self thing?
jsfiddle

Extend JavaScript Object to init at same time

What's the best way to extend a function so that when it's called, it's also new extended class is called.
Take the following class:
var class = {}
class.init = function(){
//do something
};
E.g. now extend init:
class.init.prototype.extend = function(){
console.log("hey look at me, I get called too!");
}
The idea here is, when class.init() is called, we'd like the extended classes to be automatically called too. The goal is to extend the class so i.e. like binding a click event to a link but with out modifying anything from the original function.
You can overwrite the function with one that also calls the overwritten one:
(function (old) {
class.init = function() {
console.log("hey look at me, I get called before!");
var result = old.apply(this, arguments);
console.log("hey look at me, I get called after!");
return result;
};
}(class.init));
You can re-assign class.init to a proxy function that calls the original function as well as your new one.
Something like this:
var class = {}
class.init = function(){
//do something
};
(function(){
var _old = class.init;
class.init = function(){
console.log("hey look at me, I get called too!");
return _old.apply(this, arguments);
};
}());
A more generic extend method that can extend any method not just init:
Live at JSBin
function Klass(name){
this.name = name;
this.staticMethod = function(){console.log('static method at Klass');};
}
Klass.prototype.someMethod = function(){console.log('Klass.someMethod');};
Klass.extend = function(extention){
function extendMethod(method1, method2){
var args = arguments;
var contex = this;
return function(){
method1.apply(contex, args);
method2.apply(contex, args);
};
}
var proto = new Klass();
var Extended = function(){Klass.apply(this, arguments);};
for(var key in extention){
if(typeof proto[key] === 'function' && typeof extention[key] === 'function'){
var oldMethod = proto[key];
proto[key] = extendMethod(oldMethod, extention[key]);
}
}
Extended.prototype = proto;
return Extended;
};
var ExKlass = Klass.extend({
someMethod: function(){
console.log('ExKlass.someMethod');
}
});
var k = new Klass();
var ek = new ExKlass();
k.someMethod();
ek.someMethod();

OO Javascript Question

Given the following:
var someObject = {};
someObject.prototype.a = function() {
};
someObject.prototype.b = function() {
//How can I call someObject.a in this function?
};
How can I call someObject.a from someObject.b? Thanks.
This will work:
someObject.prototype.b = function() {
this.a();
};
However your definition of someObject is slightly wrong, it should be:
var someObject = function() {};
Test script:
var someObject = function() {};
someObject.prototype.a = function() {
alert("Called a()");
};
someObject.prototype.b = function() {
this.a();
};
var obj = new someObject();
obj.b();
I think you probably meant to do this:
function Thingy() {
}
Thingy.prototype.a = function() {
};
Thingy.prototype.b = function() {
this.a();
};
var someObject = new Thingy();
It's constructor functions, not plain objects, that have a special prototype property. The prototype of a constructor function is assigned to all objects created with that constructor via the new keyword as their underlying prototype, which gives them default properties (which may reference functions, as they do above).

Categories