Call normal function and function in array Javascript - javascript

my code:
var myc = {
utils: {
my_fnc: function(a) {
console.log('This is: '+a);
}
},
run: function(type, name, args) {
if (type == 1) {
//call function in myc.utils
return myc.utils[name].apply(myc.utils, args);
} else {
//call global function
return name.apply(null, args);
}
}
};
function myFnc(a) {
console.log('This is: '+a);
}
example 1:
myc.run(1, my_fnc, new Array('a value'));
it working.
example 2:
myc.run(2, myFnc, new Array('a value'));
it not working, this is error: Uncaught TypeError: undefined is not a function
somebody can help me?

Related

How to prevent object properties to not be extended in javascript

Im trying to seal an object property .
My question is ,here i have given Object.seal(personObject),this particular object is sealed and does not allow to configure or make any extensions in this object,but as i did not mention on personObject_2 it does allow to extend or configure
How can i make it on prototype .I mean like any class of type person should have/respect this seal.Can we achieve such behaviour
"use strict";
var personModule=(function (module) {
var person=function (fname,lname) {
Object.defineProperty(this,'firstName',{
get:function () {
return fname;
}
,set:function (newValue) {
fname=newValue;
},
configurable:true
});
Object.defineProperty(this,'lastName',{
get:function () {
return lname;
}
,set:function (newValue) {
lname=newValue;
},
configurable:true
});
Object.defineProperty(this,'fullName',{
get:function () {
return fname+lname;
},
configurable:true
});
}
module.person=person;
return module;
})(personModule || {});
var personObject=new personModule.person( "Raju","Rani");
console.log(personObject.fullName);
Object.seal(personObject);
//delete personObject.firstName;-->It throws error here
var personObject2=new personModule.person( "Shiva","Kumar");
delete personObject2.firstName;
console.log(personObject2.firstName);
Thanks
Here is Proxy version in case you do not prefer adding Object.seal on constructor
"use strict";
var personModule=(function (module) {
var person=function (fname,lname) {
Object.defineProperty(this,'firstName',{
get:function () {
return fname;
}
,set:function (newValue) {
fname=newValue;
},
configurable:true
});
Object.defineProperty(this,'lastName',{
get:function () {
return lname;
}
,set:function (newValue) {
lname=newValue;
},
configurable:true
});
Object.defineProperty(this,'fullName',{
get:function () {
return fname+lname;
},
configurable:true
});
}
module.person=new Proxy(person, {
construct(target, args){
args.unshift(null);
let ctor = target.bind.apply(target, args);
let result = new ctor();
Object.seal(result);
return result;
}
});
return module;
})(personModule || {});
var personObject=new personModule.person( "Raju","Rani");
console.log(personObject.fullName);
Object.seal(personObject);
//delete personObject.firstName;-->It throws error here
var personObject2=new personModule.person( "Shiva","Kumar");
delete personObject2.firstName;
console.log(personObject2.firstName);
Did you tried - immutable-js
var personObject = new personModule.person("Raju", "Rani");
var sealed = Immutable.Map(personObject);

Javascript wrong binding: function disappear but variables ok

The problem is that when I am binding this to function in .then() of Promise all variables is binded but 1 which is function, not.
define([
'Service/service',
'core/widget'], function (service, widget) {
return widget.extend({
init: function (options) {
this.options = options;
console.log('this.options: ', this.options); //{actionToDo:function(),variables...}
service.getFile('app/Core/Widgets/Button/Views/button.html')
.then(
function(){
console.log('this.options: ', this.options); //{actionToDo:undefined,...}
}.bind(this)
)
}
});});
I am creating the object by:
new Button(
{
elementToAppend: this.className + ' .actions > .actionButtons',
class: action.class,
icon: action.icon,
text: action.text,
unique: action.unique,
actionToDo: function(){//some code}
}
);
And the widget:
define(['underscore'], function (_) {
function Widget() {
}
return {
extend: function (methods) {
var widget = new Widget();
widget.prototype = {
trigger: function (event) {
switch (event) {
case 'click':
{
this.onClick.call(this);
break;
}
}
}
};
var Widget_Extended = _.extend(widget.prototype, methods);
return function (options) {
Widget_Extended.init(options);
return Widget_Extended;
};
}
};});
Could you tell me why inside function in .then() 1 parametr of options is undefined?
The solve of the problem (I guess) is:
define(['underscore'], function (_) {
function Widget() {
}
return {
extend: function (methods) {
return function (options) {
var widget = new function () {
};
widget.prototype = {
trigger: function (event) {
switch (event) {
case 'click':
{
this.onClick.call(this);
break;
}
}
}
};
var Widget_Extended = _.extend(widget.prototype, methods);
Widget_Extended.init(options);
return Widget_Extended;
};
}
};});

Console logging "this" returns "null"

I am trying to create a flux store for a React app I am building. I am using an object-assign polyfill npm package and Facebook's Flux library.
Initially I was getting the error "Cannot read property '_data' of null' error in the console which was refering to var currIds = this._data.map(function(m){return m.id;});. That method is currently the only one being called directly. I then did console.log(this) which returned "null".
I find this strange. What is going on?
My code:
var Assign = require('object-assign');
var EventEmitterProto = require('events').EventEmitter.prototype;
var CHANGE_EVENT = 'CHANGE';
var StoreMethods = {
init: function() {},
set: function (arr) {
console.log(this);
var currIds = this._data.map(function(m){return m.id;});
arr.filter(function (item){
return currIds.indexOf(item.id) === -1;
}).forEach(this.add.bind(this));
},
add: function(item){
console.log(this);
this._data.push(item);
},
all: function() {
return this._data;
},
get: function(id){
return this._data.filter(function(item){
return item.cid === id;
})[0];
},
addChangeListener: function(fn) {
this.on(CHANGE_EVENT, fn);
},
removeChangeListener: function(fn) {
this.removeListener(CHANGE_EVENT, fn);
},
emitChange: function() {
this.emit(CHANGE_EVENT);
},
bind: function(actionType, actionFn) {
if(this.actions[actionType]){
this.actions[actionType].push(actionFn);
} else {
this.actions[actionType] = [actionFn];
}
}
};
exports.extend = function(methods) {
var store = {
_data: [],
actions: {}
};
Assign(store, EventEmitterProto, StoreMethods, methods);
store.init();
require('../dispatcher').register(function(action){
if(store.actions[action.actionType]){
store.actions[action.actionType].forEach(function(fn){
fn.call(null, action.data);
})
}
});
return store;
};
I can't see where set is called, however your this can be null if the function is invoked through call (see here) or apply, and your first argument is null.
This also happens in your require.register callback:
fn.call(null, action.data) //First parameter is your 'this'.

How to Handle CallBack Functions in AngularJs?

In controller, i am returning object from factory. The method is callback type.
But the problem is that the object is not returing.
My implementation is as:
.factory('fileReadFactory', ['$http',
function ($http) {
var objRead = {
setReadObject: '',
setPath: 'comMyTaxi',
setFileName: '',
status: false,
errorCode: ''
};
var factory = {};
factory.fileRead = function RequestFileSystem(fileName) {
alert('factory start');
objRead.setFileName = fileName;
try {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, createDirectory, fail);
objRead.status = true;
return objRead;
} catch (e) {
return objRead;
}
}
///write steps starts
function createDirectory(fs) {
fs.root.getDirectory(objRead.setPath, {create: true, exclusive: false}, onSuccessCreateFile, fail);
}
function onSuccessCreateFile(dirEntry) {
dirEntry.getFile(objRead.setFileName + '.txt.gz', null, gotFileEntryRead, fail);
}
function gotFileEntryRead(fileEntry) {
// alert('in 2 type step2');
fileEntry.file(gotFileReading, fail);
}
function gotFileReading(file) {
// alert('in 2 type step3');
readFile(file);
}
function readFile(file) {
// alert('in 2 type step4');
var reader = new FileReader();
reader.onloadend = function (e) {
// alert("Text is: "+this.result);
objRead.setReadObject = this.result;
}
reader.readAsText(file);
// alert('reading Ends');
}
//write file ends
function fail(err) {
alert('error ' + err.code);
objRead.errorCode = err.code;
throw e;
}
return factory;
}]);
And my call inside controller is like
var objReturn = fileReadFactory.fileRead('myProfile');
alert(objReturn.status);
alert(JSON.parse(objReturn.setReadObject));
if(objReturn.status){
var obj= JSON.parse(objReturn.setReadObject);
// alert(obj);
// alert('Inside Object World');
$scope.myprofile = obj;
}
I am not getting the if block. So how do i manage the call back;
Try to call your service and execute the alerts in then() function. You should also read about promises: http://andyshora.com/promises-angularjs-explained-as-cartoon.html
var objReturn = fileReadFactory.fileRead('myProfile').then(function(){
alert(objReturn.status);
alert(JSON.parse(objReturn.setReadObject));
if(objReturn.status){
var obj= JSON.parse(objReturn.setReadObject);
// alert(obj);
// alert('Inside Object World');
$scope.myprofile = obj;
}
});

javascript variable access error

I have the code snippet below:
var ret_ = function(x){
return x;
}
var make_cps=function(x,c_){
return c_(x);
}
var pred = {
_position: 0,
setPosition: function (i) {
_position = i
},
getPosition: function () {
return _position
},
_size: 0,
setSize: function (i) {
_size = i
},
getSize: function () {
return _size
},
_context: null,
setContext: function (x) {
_context = x
},
run: function () {
return function (c_) {
return make_cps(_position, c_);
}(ret_) == 2;
}
}
When I run it like below, it runs correctly:
pred.setPosition(2)
pred.setSize(10)
pred.setContext(null)
var res = pred.run()
console.log(res) // Output: true
but if I replace the _position to getPosition() an error occurs as getPosition() is not defined. Also if I change to this.getPosition() it says this doesn't have a member called getPosition()
var pred = {
_position: 0,
setPosition: function (i) {
_position = i
},
getPosition: function () {
return _position
},
_size: 0,
setSize: function (i) {
_size = i
},
getSize: function () {
return _size
},
_context: null,
setContext: function (x) {
_context = x
},
run: function () {
return function (c_) {
return make_cps(this.getPosition(), c_); // gives Error here
}(ret_) == 2;
}
}
Please someone throw light on this issue.
You've lost your context. Where you've put this.getPosition(), this will return as the window object.
If you alter the line to read
return make_cps(pred.getPosition(), c_);
It will work successfully.
Alternately, you can change the run function to read
run: function () {
var that = this;
return function (c_) {
return make_cps(that.getPosition(), c_);
}(ret_) == 2;
}
Edit: Clarification
The reason that _position is still working rather than suffering from the same issue is that you're not actually setting prev._position at all in your current code.
setPosition: function (i) {
_position = i
},
getPosition: function () {
return _position
}
What it's actually doing there is creating a new global variable called _position and using that instead.
This code should actually read:
setPosition: function (i) {
this._position = i
},
getPosition: function () {
return this._position
},
This is setting a global variable _position:
setPosition: function (i) {
_position = i
},
It is not the variable on your pred object.
When you access it here:
run: function () {
return function (c_) {
return make_cps(_position, c_);
}(ret_) == 2;
}
you're using that global variable.
If you want to use instance properties, you're going to need to start using this:
setPosition: function (i) {
this._position = i
},
run: function () {
var pred = this;
return function (c_) {
return make_cps(pred._position, c_);
}(ret_) == 2;
}

Categories