How to change the properties with factory method in javascript - javascript

i have one class i am trying to overwrite it with factory design pattern but not able to do that..
how to call it exactly to change the properties of object
function othername() {
var newobj = new Object();
newobj.fname = "sachin",
newobj.lname = "rawal",
newobj.fullname = function () {
alert(this.fname);
}
return newobj
}
var othername1 = othername ("hi","hello");

Using prototype you can do it.
function othername() {
var newobj = new Object();
newobj.fname = "sachin",
newobj.lname = "rawal",
newobj.fullname = function () {
alert(this.fname);
}
return newobj
}
var othername1 = othername ("hi","hello");
prototype:
othername.prototype.middleName = "middleNameString";
var named = othername();
var md = named.middleName // md == "middleNameString"

function Othername(fname,lname) {
this.fname = fname || "sachin";
this.lname = lname || "rawal";
};
Othername.prototype.fullname = function (){
alert(this.fname + " " + this.lname);
};
var othernameDefault = new Othername (); //sachin rawal
var othername1 = new Othername ("hi","hello"); //hi hello

Related

Set value into object with function (java script)

When I used getFullName, getFirstName and getLastName work ok, but I can't use set functions setFullName, setLastName, setFirstName. My code:
var Person = function(firstAndLast) {
var fn=firstAndLast.split(' ');
var fstr=fn.join(' ');
var frn=fn[0];
var lsn=fn[1];
this.getFullName=function(){return fstr;};
this.getFirstName=function(){return frn;};
this.getLastName=function(){return lsn;};
this.setFirstName=function(a){fn[0]=a;};
this.setLastName=function(b){fn[1]=b;};
this.setFullName=function(c){fn=c.split(' ');};
};
What about this:
var Person = function(firstAndLast) {
var self = this;
this.fn = firstAndLast.split(' ');
this.frn = this.fn[0];
this.lsn = this.fn[1];
this.getFullName=function(){return self.fn.join(' ');};
this.getFirstName=function(){return self.frn;};
this.getLastName=function(){return self.lsn;};
this.setFirstName=function(a){self.frn=a; self.fn[0]=a;};
this.setLastName=function(b){self.lsn=b; self.fn[1]=b;};
this.setFullName=function(c){
self.fn = c.split(' ');
self.frn = this.fn[0];
self.lsn = this.fn[1];};
};
See this fiddle
If you have a lot of Person objects, you should consider moving the getter/setter functions to the class prototype:
var Person = function(firstAndLast) {
this.fn = firstAndLast.split(' ');
this.frn = this.fn[0];
this.lsn = this.fn[1];
};
Person.prototype.getFullName = function() {
return this.fn.join(' ');
}
Person.prototype.getFirstName = function() {
return this.lsn;
}
Person.prototype.getLastName = function() {
return this.lsn;
}
Person.prototype.setFirstName = function(a) {
this.frn=a;
this.fn[0]=a;
}
Person.prototype.setLastName = function(b) {
this.lsn=b;
this.fn[1]=b;
}
Person.prototype.setFullName = function(c) {
this.fn = c.split(' ');
this.frn = this.fn[0];
this.lsn = this.fn[1];
}
See updated fiddle

javascript access "this" in function constructor

I'm trying to create a function constructor:
var obj = function() {
this.num = 2;
this.func = function() {
// need to access the **instance** num variable here
};
};
var instance = new obj();
I need to access the instance properties from a propery (which is the function func) of the object. But it doesn't work, since this is always the current function..
Store this in a variable which func can access:
var obj = function() {
var _this = this;
_this.num = 2;
_this.func = function() {
console.log(_this.num);
};
};
Please, use well-known approach, store this into separate field:
var obj = function() {
self = this;
self.num = 2;
self.func = function() {
alert(self.num);
// need to access the **instance** num variable here
};
};
var instance = new obj();
This is the pattern I use for the problem:
var obj = function(){
var self = this;
this.num = 2;
this.func = function() {
console.info(self.num);
};
};
var instance = new obj();
The variable self now can be accessed in all function of obj and is always the obj itself.
This is the same then:
var obj = function(){
var self = this;
self.num = 2;
self.func = function() {
console.info(self.num);
};
};
var instance = new obj();
You can do it using the Custom Constructor Functions, used to create a custom constructor and it's accessed without any problem, try it:
var Obj = function () {
this.num = 2;
this.func = function () {
alert("I have " + this.num);
return "I have " + this.num;
};
};
var instance= new Obj();
instance.func();//will return and show I have 2

OO Javascript Game, how can i add players the game's player array?

Here is the beginning of a very simple object oriented javascript game. I am having trouble adding players to the Games players[] array. how can this be done?
i've removed all the code not relevant to the question
var BobsGame = function(){
this.Players = [];
}
BobsGame.prototype.addPlayer = function(Player){
//not working
Player.Game = this;
this.Players.push(Player);
Player.setId = function(this.Players.length) {
return this.Players.length;
}
return this;
}
var Player = function(name){
this.Game = null;
this.score = 0;
this.name = name;
this.id = null;
// return alert('Player ' + this.name + ' has been created');
}
var myGame = new BobsGame();
var Player1 = new Player("Tom");
var Player2 = new Player("Bob");
myGame.addPlayer(Player1);
What I think you're trying:
var BobsGame = function () {
this.Players = [];
};
BobsGame.prototype.addPlayer = function (Player) {
this.Players.push(Player);
Player.id = this.Players.length;
return this;
};
var Player = function (name) {
this.score = 0;
this.name = name;
this.id = null;
// return alert('Player ' + this.name + ' has been created');
};
var myGame = new BobsGame();
var Player1 = new Player("Tom");
var Player2 = new Player("Bob");
myGame.addPlayer(Player1);
The error was in the following code:
Player.setId = function(this.Players.length) {
return this.Players.length;
}
Here you're trying creating a function called setId, but you can't define this.Players.length as an argument. So assuming you're trying to set the id of the player to the length of the players array, you can simple assign it like this:
Player.id = this.Players.length;
By the way, I do recommend you don't call the argument of addPlayer "Player" since this will hide the already defined function Player. You might want to rename it to "player".

javascript calling the function from prototype

I am learning javascript. When I call pictureArrayAdd method I receive error Picture.pictureArrayAdd is not a function. Why?
window.onload = init;
//window.picture = new Array();
function init() {
var button = document.getElementById("addButton");
button.onclick = addPicture;
}
function Picture() {};
Picture.prototype = {
pictureArray: [],
pictureArrayAdd: function(newImage) {
this.pictureArray.push(newImage);
return this
}
}
var addPicture = function() {
var textInput = document.getElementById ("pictureName");
var newPicture = textInput.value;
Picture.pictureArrayAdd(newPicture);
}
You have to initialize an instace of your object:
var addPicture = function() {
var textInput = document.getElementById ("pictureName");
var newPicture = textInput.value;
var pic = new Picture();
pic.pictureArrayAdd(newPicture);
}
Besides - just a tip -, you can use a optional parameter on your constructor, like this:
function Picture(newImage) {
if (newImage != undefined) {
this.pictureArrayAdd(newImage);
}
};
So you have a shortcut to your pictureArrayAdd function:
var pic = new Picture("picture1.png");
See it working here.

How to "new" a returned function in Javascript

I am trying to simulate a namespace feature in Javascript.
var com = {};
com.domain = {};
com.domain.system = {};
com.domain.net = {};
com.domain.net.ip = {};
com.domain.net.ip.tcp = {};
com.domain.net.ip.udp = {};
com.domain.net.ip.ssl = {};
com.domain.util = {};
com.domain.util.timer = {};
com.domain.plugins = {};
com.domain.session = {};
com.domain.io = {};
com.domain.algorithm = {};
com.domain.debug = {};
This is the namespaces declaration. Later I will add functions to these namespaces.
This is my selector function:
For a convenient way to use namespaces, I add a function named $. This function will walk all namespaces in com. If the selected name exists, return the object.
function $ (selector) {
function digger (namespace, selector) {
for (var prop in namespace) {
if (typeof namespace[prop] == "array" || typeof namespace[prop] == "object") {
if (prop == selector) {
return namespace[prop];
}
var dig = digger(namespace[prop], selector);
if (dig != null) {
return dig;
}
} else {
if (prop == selector) {
return namespace[prop];
}
}
}
}
return digger (com, selector);
}
After that, I add a timer to namespace com.doamin.util.
com.domain.util.timer = function () {
this._handle = new InnerObj.SystemTimer(io);
return this;
};
com.domain.util.timer.prototype.expiresFromNow = function (seconds, cbHandler) {
this._handle.ExpiresFromNow (seconds, cbHandler);
};
com.domain.util.timer.prototype.wait = function (seconds, cbHandler) {
this._handle.Wait (seconds, cbHandler);
};
com.domain.util.timer.prototype.expiresAt = function (seconds, cbHandler) {
this._handle.Wait (seconds, cbHandler);
};
com.domain.util.timer.prototype.cancel = function () {
this._handle.Cancel ();
};
Usage:
1. var timer = new com.domain.util.timer (); OK
timer.expiresAt (1, {}); OK
2. var func = $("timer"); OK
var timer = new func (); OK
timer.expiresAt (1, {}); OK
But but but but but
var timer = new $("timer") (); NG
Can anyone tell me why the last new function is not working?
Try var timer = new ($("timer"))();.
Your question is not clear but I guess since $("timer") returns a function, you want a new instance of the result of $("timer") and not a new instance of $().

Categories

Resources