JS how to use 'this' to point to its parent - javascript

var data = {
data2 : {
createNew : function() {
data.data2 = 10;
// smth like `this = 10`
}
}
}
How can I use this to point to the data.data2, as I don't want to repeat data.data2?

Understand through the comments your question is actually, to access the parent from within data2 .
You would need a constructor function (root is available in data2 due to closures in javascript)
function Data(){
var root = this;
this.data2 = {
createNew : function() {
data.data2 = 10;
root.x = 10;
}
}
}
var data = new Data();
data.data2.createNew();
console.log(data.x);

Related

How to make a function assigning a value using assignment operator in jquery

Having the following function :
function ObjDataSet () {
this.header = "";
this.dataIdx = 0;
this.DataRows = [];
this.CountRow = 0;
}
....
ObjDataSet.prototype.NameString = function(argIdx, argName, argValue) {
var arrObj = this.DataRows[argIdx-1];
arrObj[argName] = argValue;
this.DataRows[argIdx-1] = arrObj;
};
And I am using this function like this after declaration:
var dataSet = new ObjDataSet();
dataSet.NameString(1, "CUST_KIND",document.searchForm.CUST_KIND.value);
But I would like to use this function like this using assignment operator :
dataSet.NameString(1, "CUST_KIND") = document.searchForm.CUST_KIND.value;
To use assignment operation, How to change "NameString" function?
I don't want to assign a value as a argument of function.
Thank you.
You cannot do what you are asking. The left hand side of an assignment must be a variable or a property of an object. The closest you can do is this:
dataSet.NameString(1).CUST_KIND = 'value';
Which assumes dataSet.NameString(1) returns an object that can have a property assigned to it. Here is a full demo:
var dataSet = setup();
// Log DataRows before and after assigning:
console.log( dataSet.DataRows );
dataSet.NameString(1).CUST_KIND = 'value';
console.log( dataSet.DataRows );
//////
// Prepare dataSet object with `DataRows[0] = {};`
function setup ( ) {
function ObjDataSet () {
this.header = "";
this.dataIdx = 0;
this.DataRows = [];
this.CountRow = 0;
}
ObjDataSet.prototype.NameString = function(argIdx, argName) {
return this.DataRows[argIdx-1];
};
const dataSet = new ObjDataSet;
dataSet.DataRows[0] = {};
return dataSet;
}

How can I make privileged JS methods?

I want to be able to call sub-functions that work with private data. Currently I have this:
var myFunction4 = function() {
this.secret1 = 0;
this.secret2 = 0;
var that = this;
this.iterate1 = function(){
return that.secret1++;
}
this.iterate2 = function(){
return that.secret2++;
}
this.addSecrets = function(){
return that.secret1 + that.secret2;
}
return {
iterate1: this.iterate1,
iterate2: this.iterate2,
addSecrets: this.addSecrets,
}
};
The bad thing about this is that to call one of the methods, I have to do:
myFunction4().iterate1();
Which executes myFunction4() every single time I want to access a method. Not only is this inefficient, but it resets secret1 each time so I can't iterate it. I've tried using the new operator, but that exposes secret1 and secret2, and it messes up the ability to nest functions deeply.
var myFunction3 = function() {
this.secret1 = 0;
this.secret2 = 0;
this.iterate1 = function(){
return this.secret1++;
}
this.iterate2 = function(){
return this.secret2++;
}
this.addSecrets = function(){
return this.secret1 + this.secret2;
}
};
var f3 = new myFunction3();
f3.secret1; // exposes the secret!
See the console logs at the bottom of this JSFiddle for more examples.
How can I have a function with both private and public vars/methods which retain their values and don't need to be called multiple times?
While the other answers are absolutely fine and correct, there is one more issue to consider when emulating OOP behaviour in javascript.
The function execution context issue will bite us hard when we will try to use a public method as a e.g. async. callback.
The magical this will point to a different object then we expect in the OOP world.
Of course there are ways to bind the context but why to worry about this after we define the 'class' in a non OOP js ;)
Here is a simple solution to this: Do not use this. Let the closure refactor this out ;)
var myFunction4 = function() {
// we could inherit here from another 'class' (object)
// by replacing `this` with e.g. `new SuperClass()`
var that = this;
// 'private' variables
var secret1 = 0;
var secret2 = 0;
// 'public' variables
that.somePublicVar = 4;
// 'private' methods
var somePrivateMethod = function(){
secret2 = 77;
that.somePublicVar = 77;
}
// 'public' methods
that.iterate1 = function(){
return secret1++;
}
that.iterate2 = function(){
return secret2++;
}
that.addSecrets = function(){
return secret1 + secret2;
}
return that;
};
var f = new myFunction4();
console.log( f.iterate1() ); // 0
console.log( f.iterate1() ); // 1
console.log( f.secret1 ); //undefined
console.log( f.somePublicVar ); //4
Try that (closures power!):
var myFunction3 = function() {
var secret1 = 0;
var secret2 = 0;
this.iterate1 = function(){
return secret1++;
}
this.iterate2 = function(){
return secret2++;
}
this.addSecrets = function(){
return secret1 + secret2;
}
};
var f3 = new myFunction3();
now only the methods are exposeds
Edited version:
If you don't wanna execute the main function every time you call sub-method, you can change a bit your approach and use the power of IIFE (immediately-invoked function expression)
var myFunction4 = (function() {
var secret1 = 0;
var secret2 = 0;
var iterate1 = function(){
return secret1++;
}
var iterate2 = function(){
return secret2++;
}
var addSecrets = function(){
return secret1 + secret2;
}
return {
iterate1: iterate1,
iterate2: iterate2,
addSecrets: addSecrets
}
}());
Then you can use this:
myFunction4.iterate1();
myFunction4.iterate2();
myFunction4.addSecrets();
Hope this helps you
I generally only use the factory pattern to create objects unless I absolutely need to have the performance benefits of prototypical inheritance.
Using the factory pattern also means you don't have to deal with the ever changing value of this in different contexts.
var factory = function() {
// internal private state
var state = {
secret1: 0,
secret2: 0
}
function iterate1(){
return state.secret1++;
}
function iterate2(){
return state.secret2++;
}
function addSecrets(){
return state.secret1 + state.secret2;
}
function __privateMethod() {
// this is private because it's not on the returned object
}
// this is the public api
return {
iterate1,
iterate2,
addSecrets
}
}
// create a secret module
var secret = factory()
console.log(
secret.iterate1(), // 0
secret.iterate2(), // 0
secret.addSecrets(), // 2
secret.secret1, // undefined
secret.secret2 // undefined
)
// you can even create more with the same factory
var secret2 = factory()
Why don't you try Revealing Module Pattern
var myFunction4 = function() {
var secret1 = 0,
secret2 = 0,
iterate1 = function(){
return secret1++;
},
iterate2 = function(){
return secret2++;
},
addSecrets = function(){
return secret1 + secret2;
};
// public functions and properties
return {
iterate1: iterate1,
iterate2: iterate2,
addSecrets: addSecrets,
}
}();
myFunction4.iterate1(); // is available
myFunction4.secret2; // is private and not available outside of myFunction4
Hope it helps
A basic pattern:
var myFunction = function() {
var that = this;
var secret1 = 0;
var secret2 = 0; // private
this.public1 = 0; // public
this.iterate1 = function(){
return secret1++;
}
this.iterate2 = function(){
return secret2++;
}
this.addSecrets = function() { // public
return privateMethod();
}
var privateMethod = function() { // private
return secret1 + secret2;
}
return this; // return function itself!
};
var myFn = new myFunction();
myFn.public1 // 0
myFn.secret1 // undefined
myFn.addSecrets();
I recommend you to read the excellent Learning JavaScript Design Patterns by Addy Osmani.
What I understand from your explanation as per your second snippet is that you need a sharedPrivate among the instantiated objects. You can not do this with classical object creation patterns like constructor, factory or module. This is possible by taking a private variable under closure in the prototype of the constructor so that it doesn't get reset each time an object is created and at the meantime the instantiated objects are provided with necessary methods to access, modify and share it privately.
function SharedPrivate(){
var secret = 0;
this.constructor.prototype.getSecret = function(){return secret}
this.constructor.prototype.setSecret = function(v){ secret = v;}
this.constructor.prototype.incrementSecret = function(){secret++}
}
var o1 = new SharedPrivate();
var o2 = new SharedPrivate();
console.log(o1.getSecret()); // 0
console.log(o2.getSecret()); // 0
o1.setSecret(7);
console.log(o1.getSecret()); // 7
console.log(o2.getSecret()); // 7
o2.incrementSecret()
console.log(o1.getSecret()); // 8
And another method of getting a similar result would be
function SharedPrivate(){
var secret = 0;
return {getS : function(){return secret},
setS : function(v){secret = v},
incS : function(){secret++}
};
}
sharedProto = SharedPrivate(); // secret is now under closure to be shared
var o1 = Object.create(sharedProto); // sharedProto becomes o1.__proto__
var o2 = Object.create(sharedProto); // sharedProto becomes o2.__proto__
o1.setS(7); // o1 sets secret to 7
console.log(o2.getS()); // when o2 access it secret is still 7
o2.incS(); // o2 increments the secret
console.log(o1.getS()); // o1 can access the incremented value

Use Javascript Object to Angular Service

I am trying to add functions to a JS Object which will be used as a singleton service.
angular
.module('app.steps')
.factory('createStepsService', createStepsService);
createStepsService.$inject = [];
/* #ngInject */
function createStepsService() {
var steps;
var service = {
newSteps: function (current_step, total_steps) {
if (!steps) {
return new Steps(current_step, total_steps);
}
}
};
return service;
function Steps(current_step, total_steps) {
this.c_step = current_step;
this.t_step = total_steps;
}
Steps.prototype = {
addSteps: function (num) {
this.c_step += num;
},
setLastStep: function () {
this.lastStep = this.c_step = this.t_step;
}
};
}
When I run this line from the controller, I am not able to access
addSteps / setLastStep methods.
vm.createStepsService = createStepsService.newSteps(1, 3);
Why I don't see these methods? Were they created?
Thanks.
Your steps.prototype code is never ran.
This is because it appears after the return.
Change the order of your code to this:
/* #ngInject */
function createStepsService() {
var steps;
function Steps(current_step, total_steps) {
this.c_step = current_step;
this.t_step = total_steps;
}
Steps.prototype = {
addSteps: function (num) {
this.c_step += num;
},
setLastStep: function () {
this.lastStep = this.c_step = this.t_step;
}
};
var service = {
newSteps: function (current_step, total_steps) {
if (!steps) {
return new Steps(current_step, total_steps);
}
}
};
return service;
}
The reason that you can have a function declared before a return is because of JavaScript variable and function hoisting.
Your problem is that you are creating Steps.prototype after a return statement, so it will never be read.
In AngularJS, services are singletons objects that are instantiated only once per app.
And the factory() method is a quick way to create and configure a service.
It provides the function's return value i.e. Need to create an object, add properties to it, then it will return that same object.
For ex:
angular
.module('myApp',[])
.factory("createStepService", function(){
var stepServiceObj = {};
var c_step = 0;
var t_steps = 0;
var last_step = 0;
stepServiceObj.setCurrentStep = function(current_step){
c_step = current_step;
console.log('c_step1: ',c_step);
};
stepServiceObj.getCurrentStep = function(){
return c_step;
};
stepServiceObj.setTotalStep = function(total_steps){
t_steps = total_steps;
};
stepServiceObj.getTotalStep = function(){
return t_steps;
};
stepServiceObj.setLastStep = function(){
last_step = c_step = t_step;
};
stepServiceObj.getLastStep = function(){
return last_step;
};
stepServiceObj.addSteps = function(num){
return c_step += num;
};
return stepServiceObj;
});

Storing variables in my name spaced javascript

If I have my name space for my app like so:
var myApp = {};
(function() {
var id = 0;
this.next = function() {
return id++;
};
}).apply(myApp);
Then if I log the following result:
console.log(myApp.next()); //1
How can I store variable within the name space function, for instance something like:
var myApp = {};
(function() {
var id = 0;
this.next = function() {
return id++;
};
// Store variables here ...
this.variableStore = function() {
var var1 = "One";
};
}).apply(myApp);
Trying to access like this:
console.log(myApp.variableStore().var1); // Gives me an error
Is this possible, or even a good idea? Or should I just declare a new name space for what are essentially global variables?
var myApp = {};
(function() {
var id = 0;
this.next = function() {
return id++;
};
// Store variables here ...
this.variableStore = function() {
this.var1 = "One";
return this;
};
}).apply(myApp);
Such declaration will add var1 property to myApp object only after variableStore() is called:
myApp.var1 //undefined
myApp.variableStore() // Object {...}
myApp.var1 //"One"
About your question: you can not actually store variable within a function. If you are trying to make a internal namespace for myApp, consider doing the following:
(function() {
var id = 0;
this.next = function() {
return id++;
};
this.subNameSpace = {
init: function () {
this.var1 = "One"
return this;
}
}
}).apply(myApp);
myApp.subNameSpace.init();
myApp.subNameSpace.var1; //"One"
(function() {
var id = 0, var1; //DECLARE VARIABLE HERE
this.next = function() {
return id++;
};
// Store variables here ...
this.variableStore = function() {
this.var1 = "One"; //NO "VAR" KEYWORD
};
}).apply(myApp);
Using var var1 = "One"; creates var1 in the local scope, so you can't access it from the instance of myApp. Also, remember to use this.var1; otherwise the variable var1 is essentially a private variable and can't be accessed from the outside.
Also, if you want to use
console.log(myApp.variableStore().var1);
Then you'll have to return myApp; in your variableStore method. This is because myApp.variableStore() currently returns nothing, so you can't access var1 of nothing. So, here is the complete code:
var myApp = {};
(function() {
var id = 0, var1;
this.next = function() {
return id++;
};
// Store variables here ...
this.variableStore = function() {
this.var1 = "One";
return myApp;
};
}).apply(myApp);
console.log(myApp.variableStore().var1);
You already got some answers on how you could use your variableStore function. But maybe it would be sufficient for you to just store your variable with the .-operator?
var myApp = {};
(function() {
var id = 0;
this.next = function() {
return id++;
};
}).apply(myApp);
//store:
myApp.var1 = "One";
//request:
console.log(myApp.var1); //One

Javascript and module pattern

i think i did not understand javascript module pattern.
I just create this module:
var mycompany = {};
mycompany.mymodule = (function() {
var my = {};
var count = 0;
my.init = function(value) {
_setCount(value);
}
// private functions
var _setCount = function(newValue) {
count = newValue;
}
var _getCount = function() {
return count;
}
my.incrementCount = function() {
_setCount(_getCount() + 1);
}
my.degreeseCount = function() {
_setCount(_getCount() - 1);
}
my.status = function() {
return count;
}
return my;
})();
var a = mycompany.mymodule;
var b = mycompany.mymodule;
console.debug(a, 'A at beginning');
console.debug(a, 'B at beginning');
a.init(5);
b.init(2);
console.log('A: ' + a.status()); // return 2 (wtf!)
console.log('B: ' + b.status()); // return 2`
Where is the mistake?
I thought that my code would have returned to me not 2 value, but 5.
What's the reason?
a and b are the exact same objects.
var a = mycompany.mymodule;
var b = mycompany.mymodule;
What you want to do is create two different objects which have the same prototype. Something similar to this:
mycompany.mymodule = (function () {
var my = function () {};
my.prototype.init = function (value) {
_setCount(value);
};
my.prototype.incrementCount = ...
// ...
return my;
}());
a = new mycompany.mymodule();
b = new mycompany.mymodule();
a.init(5);
b.init(2);
For more info, research "javascript prototypal inheritance"
In JavaScript, objects are passed by reference, not copied.
To explain further, here is a simplified version of your code:
var pkg = (function () {
var x = {};
return x;
}());
var a = pkg;
var b = pkg;
You do not create two separate objects but only reference the object pointed at by pkg from both a and b. a and b are exactly the same.
a === b // true
This means that calling a method on a you are ultimately doing the same to b (it points to the same object—x.)
You don't want to use the module pattern for this. You want the usual constructor+prototype.
function Pkg() {
this.count = 0;
};
Pkg.prototype.init = function (count) { this.count = count; };
var a = new Pkg();
var b = new Pkg();
a === b // false
a.init(2);
a.count === 2 // true
b.count === 2 // false
Here is a good read about module pattern.

Categories

Resources