(Partial) Extending "functions" in javascript? - javascript

I have this code...
var my = {
helpers: {
getName: function() {
return 'John Doe';
}
}
}
// in another file...
var my = {
helpers: {
getAge: function() {
return '40';
}
}
}
// Test...
$("#myDiv").html(my.helpers.getName + " " + my.helpers.getAge);
http://jsfiddle.net/MojoDK/8cmV7/
... but getName is undefined.
I was hoping javascript was smart enough to merge it into this...
var my = {
helpers: {
getName: function() {
return 'John Doe';
},
getAge: function() {
return '40';
}
}
}
How do I extend a method (or what it's called) like above? I have several "helper" files, that needs to "merge".

Redundancy is good for this:
my = window.my || {};
my.helpers = my.helpers || {};
my.helpers.getAge = function() {
return 40;
};
Demo of it in action

You can also use http://api.jquery.com/jquery.extend
as in:
var my = {
getName: function() {}
};
$.extend(my, {
getAge: function() {
}
});
Demo: http://jsfiddle.net/7KW3H/

Related

Catch Bound Event In IE

Get Object function name from event list on IE works fine in Chrome btw
Example
var foo = {
fookeydown:function(e){
e.which;
... do something
}
}
$(document).on("keydown",foo.fookeydown)
$._data(document,"events").keydown[0].handler.name // return me fookeydown in Chrome
but ie is nut
You are trying to access a function's property function.name, which is not defined for IE. You could try the following implementation to define it (Notice the function name given to the function in foo):
if (!(function f() {}).name) {
Object.defineProperty(Function.prototype, 'name', {
get: function() {
var name = (this.toString().match(/^function\s*([^\s(]+)/) || [])[1];
Object.defineProperty(this, 'name', {
value: name
});
return name;
}
});
}
var foo = {
fookeydown: function fookeydown(e) {
console.log(e.which, 'keydown');
console.log($._data(document, "events").keydown[0].handler.name);
}
};
$(document).on("keydown", foo.fookeydown);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Alternative, searching in foo.fooProp:
var foo = {
fooProp: {
foofookeydown: function(e) {
console.log(e.which, 'keydown');
console.log($._data(document, "events").keydown[0].handler.name);
},
init: function() {
$(document).on("keydown", this.foofookeydown);
},
},
init: function() {
this.fooProp.init()
}
};
if (!(function f() {}).name) {
Object.defineProperty(Function.prototype, 'name', {
get: function() {
var name = '';
var values = Object.keys(foo.fooProp).map(function(e) {
return foo.fooProp[e]
});
if (values.length > 0) {
if (values.indexOf(this) > -1)
name = Object.keys(foo.fooProp)[values.indexOf(this)];
}
Object.defineProperty(this, 'name', {
value: name
});
return name;
}
});
}
foo.init();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

how to get an object from a closure?

How to get an object from a closure, that's confusion with me, here is the question:
var o = function () {
var person = {
name: 'jonathan',
age: 24
}
return {
run: function (key) {
return person[key]
}
}
}
question: How do i get original person object without changing the source code.
var o = function() {
var person = {
name: 'jonathan',
age: 24
}
return {
run: function(key) {
return person[key]
}
}
}
Object.defineProperty(Object.prototype, "self", {
get() {
return this;
}
});
console.log(o().run("self")); // logs the object
This works as all objects inherit the Object.prototype, therefore you can insert a getter to it, which has access to the object through this, then you can use the exposed run method to execute that getter.
You can get the keys by running
o().run("<keyname>"))
Like that:
var o = function () {
var person = {
name: 'jonathan',
age: 24
}
return {
run: function (key) {
return person[key]
}
}
}
console.log(o().run("name"));
console.log(o().run("age"));
Could just toString the function, pull out the part you need, and eval it to get it as an object. This is pretty fragile though so getting it to work for different cases could be tough.
var o = function () {
var person = {
name: 'jonathan',
age: 24
}
return {
run: function (key) {
return person[key]
}
}
}
var person = eval('(' + o.toString().substr(30, 46) + ')')
console.log(person)
o().run("name")
It will be return "jonathan".
Simply you can make this
<script type="text/javascript">
var o = function () {
var person = {
name: 'jonathan',
age: 24
}
return {
run: function (key) {
return person[key]
}
}
}
let a = new o;
alert(a.run('name'));
</script>

javascript: extending methods between objects, like mixins

I want to share or reuse some logic between differents objects, that they will be pretty similar, just changing the "scope".
var Mixin = {
show: function () {
this.container.show();
},
hide: function () {
this.container.hide();
},
play: function (data) {
data.map().append();
}
};
var ObjectA = {
container: $('#container_a');
foo: function () {
this.play(otherData); // Mixin common method?
}
};
var ObjectB = {
container: $('#container_b'),
foo: function () {
this.play(data); // Mixin common method?
}
};
ObjectA.show() // show $('#container_a');
ObjectB.show() // show $('#container_b');
I was trying using underscore
_.extend(ObjectA, Mixin);
but it seems like I have issues with the reference of the Mixin (this reference to the last extended object), like if i need to clone the object and extend it?
Is there any approach to do something similar?
Thanks!!
EDIT: I having issue with the scope of 'this', that is referencing to window, when a pass as a callback a function inherits from the mixin, like this.
PersonMixin = {
mixinFoo: function () {
this.handleResponse();
}
};
Person = {
personMethod: function () {
OtherLibrary.libMehtod(this.mixinFoo);
}
};
Object.assign(Person, PersonMixin);
and then, something like this will fail, this an example stack trace
Person.personMethod();
OtherLibrary.libMethod(callbackMixin);
Ajax.post(callbackMixin);
callbackMixin(response); // this.handleResponse() is not defined, because this reference to window object.
EDIT 2: I can solve this issue using bind()
You can do this in a number of ways, my preference is adjusting the objects __proto__ property on creation which will cause it to inherit your mixin via its prototype chain. This does not require the use of underscore.
I adjusted your example for ES6 and made it a bit simpler but should get the point across.
const PlayerType = (
{ show() {
console.info(`show ${this.name}`)
}
, hide() {
console.info(`hide ${this.name}`)
}
, play: function (data) {
data.map().append();
}
}
)
const objA = { __proto__: PlayerType
, name: 'objA'
, foo(...args) {
this.play(...args)
}
}
const objB = { __proto__: PlayerType
, name: 'objB'
, foo(...args) {
this.play(...args)
}
}
objA.show()
objB.show()
Simpler and no ES6:
var Mixin = (
{ show() {
console.info('show ' + this.name)
}
, hide() {
console.info('hide ' + this.name)
}
}
)
var a = { __proto__: Mixin, name: 'a' }
var b = { __proto__: Mixin, name: 'b' }
a.show()
b.show()
Alternate - Does the same thing with Object.create().
var Mixin = (
{ show() {
console.info('show ' + this.name)
}
, hide() {
console.info('hide ' + this.name)
}
}
)
var a = Object.create(Mixin, { name: { value: 'a', enumerable: true } })
var b = Object.create(Mixin, { name: { value: 'b', enumerable: true } })
a.show()
b.show()
It works, just check your syntax also.
var Mixin = {
show: function() {
console.log(this.tmp);
}
}
var oA = {
tmp: 'tmpA'
}
var oB = {
tmp: 'tmpB'
}
var mA = Object.assign(oA, Mixin);
var mB = Object.assign(oB, Mixin)
mA.show();
mB.show()

Call functions from function inside an object in a javascript loop

I have a javascript object with some functions inside, I wish I could call them in a loop, something like this:
funcs: {
func1: function() {
return true;
},
func2: function() {
return false;
}
}
for(func in funcs) {
console.log(funcs[func]());
console.log(funcs[func].call());
}
Both work. But the declaration of your object is not correct. It is var object = { /*something*/};
var funcs = {
func1: function() {
return true;
},
func2: function() {
return false;
}
};
for(func in funcs) {
console.log(funcs[func]());
console.log(funcs[func].call());
}
Output
true
true
false
false

Javascript simple MVC + module pattern implementation

Here is a very basic attempt to create a "hello world"-like JS app using the module and MVC patterns.
var appModules = {};
appModules.exampleModul = (function () {
var _data = ['foo', 'bar']; // private variable
return {
view: {
display: function() {
$('body').append(appModules.exampleModul.model.getAsString());
},
},
model: {
getAsString: function() {
return _data.join(', ');
},
}
};
})();
appModules.exampleModul.view.display();
This works fine, but I'm not happy how I have to reference the model function from the view, using the full object path: appModules.exampleModul.model.getAsString(). How can I expose the public model methods to the view, so I could simply use something like model.getAsString()? Or do I need to organize the code differently?
One option is you can convert those objects into private implementations.
appModules.exampleModul = (function() {
var _data = ['foo', 'bar'];
// private variable
var _view = {
display : function() {
$('body').append(_model.getAsString());
},
};
var _model = {
getAsString : function() {
return _data.join(', ');
},
};
return {
view : _view,
model : _model
};
})();
You could do something like this:
var appModules = {};
appModules.exampleModul = (function () {
var _data = ['foo', 'bar']; // private variable
return {
view: {
display: function() {
$('body').append(this.model.getAsString());
},
},
model: {
getAsString: function() {
return _data.join(', ');
},
}
};
})();
var display = appModules.exampleModul.view.display.bind(appModules.exampleModul);
display();
Which isn't really the prettiest of solutions, but does offer a more generic solution inside the display function!

Categories

Resources