var Person = {
name: "jana",
getName: function(callBack) {
callBack();
console.log("** "+this.name);
}
}
var anotherPerson = { name: "prabu"}
I have 2 objects. I need "anotherPerson" to be bound with the Person object. Also, I want to send parameter as a function.
I have tried below methods, but its not working
Person.getName.apply(anotherPerson, function(){})
Person.getName.apply(anotherPerson)(function(){})
Use call to pass an arbitrary number of arguments to your function, or apply to pass an array of arguments:
var Person = {
name: "jana",
getName: function(callBack) {
callBack();
console.log("** " + this.name);
}
}
var anotherPerson = {
name: "prabu"
}
Person.getName.call(anotherPerson, function () {})
Person.getName.apply(anotherPerson, [function () {}])
Have you tried Object.assign ? Like so
var Person = {
name: "jana",
getName: function(callBack) {
callBack();
console.log("** " + this.name);
}
}
var anotherPerson = {
name: "prabu"
}
Object.assign(Person, anotherPerson).getName(alert)
You can use arrow function and return the name parameter to assign value to getName.
var Person = {
name: "jana",
getName: (obj) =>obj.name
}
var anotherPerson = {
name: "prabu"
}
Person.getName(anotherPerson);
console.log(Person);
Related
I want to add functions to JSON Objects, but I can't find function for assigning to all objects, only to one.
This code works with Arrays:
Object.defineProperty(Array.prototype, 'random', {
value: () => {
return this[Math.floor(Math.random() * this.length)];
},
});
I've also found this code:
const obj = {name: 'Bob'};
obj.fullName = function() { return this.name }
But that one only works for specific object, not all of them.
Is it event possible to write global functions for all JSON Objects, and if is, then how to do it?
You could add the function to Object.prototype. Note that this is not considered a very good practice because it could impact the rest of the code (like shown in the comments):
Object.prototype.fullName = function() { return this.name; };
const obj = { name: 'Bob' };
console.log(obj.fullName());
You should consider doing this instead:
const baseObject = { fullName: function() { return this.name; } };
const obj = Object.create(baseObject, { name: { value: 'Bob', writable: true } });
console.log(obj.fullName());
And if your target runtime (browser?) supports ECMAScript 6, you could also create a dedicated class for this:
class MyClass {
constructor(name) {
this.name = name;
}
fullName() { return this.name; }
}
const bob = new MyClass('Bob');
console.log(bob.fullName());
Finally, the class syntax for ECMAScript 5:
function MyClass(name) {
this.name = name;
}
MyClass.prototype.fullName = function() { return this.name; }
const bob = new MyClass('Bob');
console.log(bob.fullName());
I have a factory like this:
TestFactory= function () {
var objectName=null;
return {
SetName:function(name) {
objectName = name;
},
GetName:function() {
return objectName;
},
Init:function() {
return angular.copy(this);
}
}
}
A controller like:
TestController = function($scope) {
$scope.TestClick = function () {
var tstA = TestFactory.Init();
var tstB = TestFactory.Init();
tstA.SetName('test A')
tstB.SetName('test B')
console.log('A', tstA.GetName());
console.log('B', tstB.GetName());
}
}
In the console I get Test B for both objects.
How can I make a proper instance of this object?
I would like to use the objectName value in other functions of the factory.
Take into account that in Angular, Factories are singletons, so the instance is always the same.
You can do the following:
TestFactory= function () {
var objectName={};
return {
SetName:function(property,name) {
objectName[property] = name;
},
GetName:function(property) {
return objectName[property];
},
Clear:function(property) {
delete objectName[property]
}
}
}
Then in your controller:
TestController = function($scope, TestFactory) {
$scope.TestClick = function () {
TestFactory.SetName('a','test A')
TestFactory.SetName('b','test B')
console.log('A', TestFactory.GetName('a')); // test A
console.log('B', TestFactory.GetName('b')); // test B
}
}
Couple of issues. First your returning an object rather than a function from your factory.
app.factory('TestFactory', function() {
return function() {
var objectName = null;
var setName = function(name) {
objectName = name;
};
var getName = function() {
return objectName;
};
return {
SetName: setName,
GetName: getName
};
};
});
Then you can just instantiate like this:
var tstA = new TestFactory();
var tstB = new TestFactory();
Services and factories are singletons so I think you can achieve what you want with a more appropriate use of the factory by providing an Init function that returns the common code and unique name like so:
angular.module('app')
.factory('ServiceFactory', serviceFactory);
function serviceFactory() {
return {
Init: function (name) {
return {
objectName: name,
setName: function (name) {
this.objectName = name;
},
getName: function () {
return this.objectName;
}
};
}
};
}
This leaves the possibility to use it as a factory that can initialize many types.
You basically need to create a simple getter/setter.
angular.module('app', [])
.controller('TestController', testController)
.service('serviceFactory', serviceFactory);
testController.$inject = ['serviceFactory'];
function testController(serviceFactory) {
serviceFactory.set('A', {
name: 'test A'
});
serviceFactory.set('B', {
name: 'test B'
});
console.log(serviceFactory.getAll());
console.log(serviceFactory.get('A'));
console.log(serviceFactory.get('B'));
}
function serviceFactory() {
var
_model = {
name: ""
},
_data = {};
return {
set: function(key, data) {
_data[key] = angular.extend({}, _model, data);
},
get: function(key) {
return _data[key];
},
getAll: function() {
return _data;
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<body ng-app="app" ng-controller="testController"></body>
I have an array of objects containing references (bound by the .bind() method) to my class functions. When I access them directly, like array[3].myFunction, everything works fine. But the strange behavior occurs when I try to access these function iterating over the array. I've tried by Array.forEach(), for-in, for-of and Array.map() function, but the result is always the same - I get the first function four times. What am I doing wrong here? Thanks in advance.
var Container = function() {
this.function1 = function() {
console.log('function 1 invoked');
};
this.function2 = function() {
console.log('function 2 invoked');
};
this.function3 = function() {
console.log('function 3 invoked');
};
this.function4 = function() {
console.log('function 4 invoked');
};
this.array = [
{ key: '1', myFunction: this.function1.bind(this) },
{ key: '2', myFunction: this.function2.bind(this) },
{ key: '3', myFunction: this.function3.bind(this) },
{ key: '4', myFunction: this.function4.bind(this) },
];
};
var container = new Container();
// Just printing the results below
console.log('direct access:');
console.log(container.array[3].myFunction);
console.log('forEach:');
container.array.forEach(el => {
console.log(el.myFunction);
});
console.log('for in:');
for (let i in container.array) {
console.log(container.array[i].myFunction);
}
console.log('map:')
container.array.map(el => {
console.log(el.myFunction);
});
PLNKR: http://plnkr.co/edit/mn8iGh4F3GcJXTNWXMiJ?p=preview
Have a look below. All seems to be working.
When you do console.log(el.myFunction), it will actually print the handle and not executing it where all handle looks same as function () { [native code] }
When you invoke the function instead el.myFunction(), you can see all they are calling the right functions and print the results respectively.
You can check the function invocation below.
var Container = function() {
this.function1 = function() {
console.log('function 1 invoked');
};
this.function2 = function() {
console.log('function 2 invoked');
};
this.function3 = function() {
console.log('function 3 invoked');
};
this.function4 = function() {
console.log('function 4 invoked');
};
this.array = [
{ key: '1', myFunction: this.function1.bind(this) },
{ key: '2', myFunction: this.function2.bind(this) },
{ key: '3', myFunction: this.function3.bind(this) },
{ key: '4', myFunction: this.function4.bind(this) },
];
};
var container = new Container();
// Just printing the results below
console.log('direct access:');
container.array[3].myFunction();
console.log('forEach:');
container.array.forEach(el => {
el.myFunction();
});
console.log('for in:');
for (let i in container.array) {
container.array[i].myFunction();
}
console.log('map:')
container.array.map(el => {
el.myFunction();
});
How do I get access to the properties or method of the main object, from sub-obiect level two (sub3). If possible I would like to avoid solutions chaining return this.
Obj = function () {};
Obj.prototype = {
name: 'name',
main: function(){
console.log(this.name);
},
subobject: {
sub2: function () {
console.log(this);
},
sub3: function () {
console.log(this.name); // How access to Obj.name ??
}
}
}
o = new Obj();
o.main(); // return name
o.subobject.sub2(); // return subobject
o.subobject.sub3(); // return undefined
With your current syntax, you can't. Because for sub2 and sub3, the this variable is Obj.prototype.subobject.
You have multiple choice:
The obvious one: don't use a suboject.
Create subobject, sub2 and sub3 in the constructor
Obj = function() {
var self = this;
this.subobject = {
sub1: function() { console.log(self); }
}
}
Use bind at each call:
o.subobject.sub2.bind(o)();
I am creating an extension function:
jQuery.fn.openCreatePersonModal = function (arg1, personHandler) {
var person = { "displayName": "john" };
personHandler(person);
return this;
}
But can't use it, neither this way:
$("<div></div>").openCreatePersonModal({
arg1: "bla",
personHandler: somePreviouslyCreatedFunction
});
Nor this way:
$("<div></div>").openCreatePersonModal({
arg1: "bla",
personHandler: function(person) { ... }
});
I'm getting:
undefined is not a function
So it is not recognizing somePreviouslyCreatedFunction as a function.
If one wants to use named arguments, should use 1 argument and interpret it as an object
jQuery.fn.openCreatePersonModal = function (args) {
var person = { "displayName": "john" };
args.personHandler(person); // <-- notice "args."
return this;
}