How to extends a javascript object? - javascript

I made a simple example of my problem with a babel object :
function babel(){
this.english = {
hello: function () { alert('hello'); },
goodbye: function () { alert('goodbye'); }
teeshirt: function () { alert('T-shirt'); }
}
}
Now, I want to extends this object :
babel.prototype.french = {
bonjour: function () { alert('bonjour'); },
aurevoir: function () { alert('au revoir'); }
}
But what if I need to use an existing function define before ?
babel.prototype.french = {
bonjour: function () { alert('bonjour'); },
aurevoir: function () { alert('aurevoir'); },
teeshirt: function () { this.english.teeshirt(); }
}
What I could do is :
var say = new babel();
(function (_this) {
babel.prototype.french = {
bonjour: function () { alert('bonjour'); },
aurevoir: function () { alert('aurevoir'); },
hello: function () { _this.english.hello(); }
}
})(say);
But in this case, I will always use the context of the say object, isn't it ?

The problem is, that in teeshirt function call this points to the french object, not babel object. If you have to access parent object, you should store reference to it somewhere. For example you can change your constructor like this:
function babel(){
this.english = {
parent: this,
hello: function () { alert('hello'); },
goodbye: function () { alert('goodbye'); }
teeshirt: function () { this.parent.french.something(); }
}
}
But as you can see, there is a problem if you don't create object in constructor. I don't see any 'nice' approach, but you can do this:
function babel(){
this.english = {
parent: this,
hello: function () { alert('hello'); },
goodbye: function () { alert('goodbye'); }
teeshirt: function () { this.parent.french.something(); }
};
for (var i in babel.prototype) {
this[i].parent = this;
}
}
Then your french will look like this:
babel.prototype.french = {
bonjour: function () { alert('bonjour'); },
aurevoir: function () { alert('aurevoir'); },
teeshirt: function () { this.parent.english.teeshirt(); }
}

While the question as asked does bring up all the fascinating issues with JavaScript's this and prototypal inheritance, I would suggest simplifying the whole problem and refactoring your objects. There are a couple ways to do this.
If the English version of teeshirt is the default, it should be in the object which is at the end of the prototype chain. That is, a French object would have as its prototype an English object. The French object would simply not contain a teeshirt member. This is similar to the way resource bundles work.
Now this idea may not work for you, because the relationship among the different bundles may be complex: perhaps sometimes Engish is a fallback sometimes but not other times. In this case, see if you can make your babel objects all singletons (i.e., just plain objects).
var babel = {}
babel.english = {
hello: function () { alert('hello'); },
goodbye: function () { alert('goodbye'); },
teeshirt: function () { alert('T-shirt'); }
}
babel.french = {
bonjour: function () { alert('bonjour'); },
aurevoir: function () { alert('aurevoir'); },
teeshirt: function () { babel.english.teeshirt(); }
}
babel.english.teeshirt();
babel.french.teeshirt();
Try it at http://jsfiddle.net/yRnLj/
I realize this looks like a complete avoidance of your interesting question. But if you only need one copy of each language bundle, it is a lot simpler. :-)

Related

Vue use object value as method name

Is it possible what I am trying to achieve here to use a value from an object as a method name?
This works great:
Vue.mixin({
methods: {
name: function () {
console.log('hello')
}
}
});
But this:
options = {
methodName: 'name'
};
const method = options.methodName;
Vue.mixin({
methods: {
method: function () {
console.log('hello')
}
}
});
Gives me the following error:
Property or method "name" is not defined on the instance but referenced during render.
Vue.mixin({
methods: {
[method]: function () {
console.log('hello')
}
}
});
will work. And you can spare assigning a constant by using
methods: {
[options.methodName]: function() {...}
}

How to get the parent function name of the function being called

I am trying to get the name of the parent function of the function being called.
For example if I have these functions:
var functions = {
coolfunction1: {
add: function () {
},
delete: function () {
},
save: function () {
}
},
coolfunction2: {
add: function () {
// i want to console.log() the name of the parent of this function,
// output: coolfunction2
},
delete: function () {
},
save: function () {
}
}
}
When I call functions.coolfunction2.add(), is there a way to log the name of the parent function that was run?
I know I can use the variable this but that only outputs the names of the children functions, add(), delete(), save().
How can I know that the coolfuntion2 was run?
I know this can be done manually, by rewriting the function name in the add() function, but is there a way to get the name dynamically?
You can add a getter to those methods as
Object.keys(functions).forEach(t =>
Object.keys(functions[t]).forEach(t2 => {
var func = functions[t][t2]; //save a reference to function since it won't be a function anymore once a getter is assigned
Object.defineProperty(functions[t], t2, {
get: function() {
console.log(t); //print the name of parent property or grand-parent property, etc
//func();
return func; //return the reference to this function
}
});
})
);
Demo
var functions = {
coolfunction1: {
add: function() {
},
delete: function() {
},
save: function() {
}
},
coolfunction2: {
add: function() {
console.log("a is invoked");
},
delete: function() {
},
save: function() {
}
}
};
Object.keys(functions).forEach(t =>
Object.keys(functions[t]).forEach(t2 => {
var func = functions[t][t2];
Object.defineProperty(functions[t], t2, {
get: function() {
console.log(t);
//func();
return func;
}
});
})
);
functions.coolfunction2.add();
functions.coolfunction2.add();
functions.coolfunction1.add();

RequireJS and Prototypal Inheritance

I'm running into an issue with using RequireJS and Prototypal inheritance. Here's my module:
define(function () {
function Module(data) {
this.data = data;
}
Module.prototype.getData = function () {
return this.data;
};
Module.prototype.doSomething = function () {
console.log(this.data);
console.log(this.getData());
};
return Module;
Module.prototype.callFunction = function (fn) {
if (this[fn]) {
console.log('call');
Module.prototype[fn]();
}
};
});
Then I instantiate the module, like so:
var module = new Module({ name: 'Marty' });
module.getData(); // returns { name: 'Marty' }
module.data; // returns { name: 'Marty' }
module.callFunction('doSomething') // returns undefined on the first (and second) console log
The console.logs in the module.doSomething() always return undefined. Am I misunderstanding how prototypal inheritance works with RequireJS?
As it turns out, I had written the callFunction method incorrectly. The correct way is:
Module.prototype.callFunction = function (fn) {
if (this[fn] && typeof this[fn] === "function") {
this[fn]();
}
};
The problem was using Module.prototype instead of this. Whoops.

Accessing javascript object property within nested function

Good day,
I have created an object that will manage data access. My app will be using a couple different datastores, so I have created a simple factory to switch between providers:
var dataProvider = {
company: {
getAllCompanies: function (callback) {
var impl = factory.createProvider(implInstance.current)
impl.company.getAllCompanies(callback);
}
}
projects: {
getAllProjects: function (callback) {
var impl = factory.createProvider(implInstance.current)
impl.projects.getAllProjects(callback);
}
}
}
That is all well and good, but I'd rather have my impl variable at the dataProvider level. I'm unsure how I would properly access it though, as 'this' doesn't provide me the right scope when I'm nested so deeply. I'd like something like the following:
var dataProvider = {
impl: function () { return factory.createProvider(implInstance.current) },
company: {
getAllCompanies: function (callback) {
//THIS WON'T WORK
this.impl.company.getAllCompanies(callback);
}
}
Thanks!
You'd want to use the module design pattern for this:
var dataProvider = (function () {
var getImpl = function () {
return factory.createProvider(implInstance.current);
};
return {
company: {
getAllCompanies: function (callback) {
getImpl().company.getAllCompanies(callback);
}
},
projects: {
getAllProjects: function (callback) {
getImpl().projects.getAllProjects(callback);
}
}
}
})();

how to call a internal javascript function in object notation

Solution:
Yay, using this.setName() worked!
Problem:
1) Didn't know how to properly title this question
2) I am trying to call a setName() from inside of getName()
Javascript:
window.login
chat = {
setName: function( ) {
},
getName( ) {
//i want to call setName() here, is that possible?
//i tried chat.setName() and setName(), both failed.
}
}
Very simple question, I just am not too knowledgeable in JavaScript. Thank you for the suggestions/help/advice!
Use this. It refers to the current object:
chat = {
setName: function() {
alert('setName');
},
getName: function() {
this.setName();
}
};
you can use the 'this' keyword.
var chat = {
setName: function(){...},
getName: function(){ this.setName(); }
};
chat = {
setName: function( ) {
alert('test');
},
getName: function( ) {
this.setName();
}
};
chat.getName();
You have a syntax error. Try:
chat = {
setName: function() {...},
getName: function() {
chat.setName();
}
}

Categories

Resources