I need a way to rewrite a javascript variable which I have written.
Here is what I have:
var TEST = new function() {
var a = 'a';
var b = 'b';
this.c = 'c';
this.getC = function() {
return this.c;
}
};
I am not very comfortable with the new keyword in front of the function(which even jslint/jshint do not like much).
I do not want key:value pair notation, which can be achieved with this code:
var TEST = function() {
return {
a : 'a',
b : 'b',
c : 'c',
getC : function() {
return this.c;
}
}
}();
Please suggest any better way, other than the key:value pair notations.
Fiddle link depicting the above problem.
http://jsfiddle.net/dizel3d/u1w6m9tb/3/ JSHint valid.
var TEST = (function() {
function Test() {
var a = 'a';
var b = 'b';
this.c = 'c';
this.getC = function() {
return this.c;
};
}
return new Test();
})();
Make it into a class:
function Thing(){
this.a="a";
this.b="b";
this.c="c";
}
Thing.prototype.getC=function(){return this.c;}
(new Thing()).getC(); //"c"
Related
a = function(x){
this.c = x;
this.c();
}
a.prototype.b = function () {
alert("B");
}
a.prototype.c = function () {
//overwrite this
}
var z = new a(this.b);
I know using this.b is wrong but is there anyway I can reference an objects method and pass it as an argument when instantiating the object?
I know the object instance doesn't exist yet but the prototypes do.
I can't paste the context as it's far too complicated I'm afraid. Basically I want to overwrite prototype.b on some occasions and do that at the instantiation point rather than afterwards. Mainly for prettier code. But if can't be done no worries.
You would need to reference it from the constructor.
a = function(x) {
this.c = x;
this.c();
}
a.prototype.b = function() {
alert("B");
}
var z = new a(a.prototype.b);
or maybe it would be nicer to send the name of the desired method, and have the constructor do it.
a = function(x) {
if (x in a.prototype) {
this.c = a.prototype[x];
this.c();
}
}
a.prototype.b = function() {
alert("B");
}
var z = new a("b");
I have created a class-like structure with a private variable. The code is as follows:
var sinan = function(){
var a = {ssss: 1};
return {
get: function(){
return a;
},
set: function(s){
a = {ssss: s}
}
}
}
When I do
sinan().get(); // outputs {ssss: 1}
sinan().set(2);
sinan().get(); // outputs {ssss: 1}
It didn't output {ssss: 2}. Does anyone know what is happening? Thanks.
Since your "class" is not singleton sinan() constructs new instance every time with a.sss being equal to 1.
What you want to do is to create only once instance and use it:
var s = sinan();
console.log( s.get() );
s.set(2);
console.log( s.get() );
Of course you can make sinon singleton too if you want. For example, here is a simple implementation with instance stored in closure:
var sinan = function () {
var instance;
return function () {
if (!instance) {
instance = function() {
var a = {ssss: 1};
return {
get: function () {
return a;
},
set: function (s) {
a.ssss = s
}
}
}();
}
return instance;
};
}();
So in this case sinan() === sinan(), i.e. sinan() returns the same object every time.
Demo: http://jsfiddle.net/r07wgyjt/
Your problem is that each time you call sinan(), a new sinan instance is created, so it's the same as :
var s1 = sinan();
s1.get(); // 1
var s2 = sinan() ;
s2.set(2); // 2
var s3 = sinan();
s3.get(); // 3
You should be doing :
var s1 = sinan();
s1.get(); // 1
s1.set(2); // 2
s1.get(); // 2
I want add new function after i have created objects . I try write some code but it not right.
//
Sorry my description don't clear. I want after i create an object i can add function for this object to do something. Hope someone can understand my english :(
http://fiddle.jshell.net/7LnLerdt/
function Add(a,b){
var _self = this;
var a = a;
var b = b;
}
Add.prototype.doAdd = function(){
var rs = this.a+this.b;
if(rs < 10){
this.lessThanTen();
}else{
this.moreThanTen();
}
};
Add.prototype.moreThanTen = function(callback) {
if(callback){
callback.call(this);
}
};
Add.prototype.lessThanTen = function(callback) {
if(callback){
callback.call(this);
}
};
var add = new Add();
add.moreThanTen(function(){
console.log("moreThanTen");
});
add.lessThanTen(function(){
console.log("lessThanTen")
});
add.doAdd();
The code where you are "assigning" callbacks is not how it works. It just executes the method, it does not magically just assign the callback. The callbacks would need to be passed into the doAdd method or you need to assign the callbacks in a different manner.
If you want to add properties to object use this code instead:
function Add(a,b){
this.a = a;
this.b = b;
}
If you want to add callbacks use this:
Add.prototype.addCallbacks(less, more) {
this.less = less;
this.more = more;
};
Add.prototype.moreThanTen = function(callback) {
if(this.more){
this.more.call(this);
}
};
Add.prototype.lessThanTen = function(callback) {
if(this.less){
this.less.call(this);
}
};
and then
var add = new Add();
add.addCallbacks(function(){
console.log("lessThanTen")
}, function(){
console.log("moreThanTen");
});
You have a couple of problems. First, using var will declare a local variable, so it will not be accessible outside that function. If you want to create a member variable, use this. instead (as jcubic pointed out).
function Add(a, b) {
this.a = a;
this.b = b;
}
Second, you are not adding the callbacks correctly. Your code is executing the callback immediately, but (I think) what you really want to do is save the callback and execute it later.
function Add(a, b) {
this.a = a;
this.b = b;
this.moreThanTenCallbacks = [];
this.lessThanTenCallbacks = [];
}
Add.prototype.moreThanTen = function(callback) {
moreThanTenCallbacks.push(callback);
};
Add.prototype.lessThanTen = function(callback) {
lessThanTenCallbacks.push(callback);
};
Add.prototype.executeCallback = function(callbacks) {
for (var i = 0; i < callbacks.length; ++i) {
if (callback) {
callback();
}
}
};
Add.prototype.doAdd = function() {
var rs = this.a + this.b;
if (rs < 10) {
this.executeCallback(this.lessThanTenCallbacks);
} else {
// NOTE: this will execute moreThanTen callbacks even if the result equals 10!
// Are you sure that is what you want?
this.executeCallback(this.moreThanTenCallbacks);
}
};
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.
How do I access 'a' below?
var test = function () {
return {
'a' : 1,
'b' : this.a + 1 //doesn't work
};
};
You can't do it this way. When you are in the process of constructing an object (that's what you actually do using the curly braces), there is no way to access it's properties before it is constructed.
var test = function () {
var o = {};
o['a'] = 1;
o['b'] = o['a'] + 1;
return o;
};
var t = function ()
{
return new x();
};
var x = function ()
{
this.a = 1;
this.b = this.a + 1; //works
}
abstract a layer
edited for formatting, and noting that this is shifting from OLN
You can't Object Literal Notion does not support this access
var test = function () {
//private members
var a = 1;
var b = a + 1;
//public interface
return {
geta : function () {
return a;
},
getb : function () {
return b;
}
}
}();