Set value into object with function (java script) - javascript

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

Related

How to override a function in a Javascript class, and call the base function

Is it possible to override a function in a Javascript class, and call it's base implementation? I've achieved this by using prototypes, but I'm trying to preserve privacy for some of the data.
This is what I have so far, and it doesn't work. I can see why it doesn't work, but I can't see a way to resolve it. I'm beginning to wonder if this is not possible in javascript (without jumping through a lot of hoops).
Also, I need to support IE11, so can't use ES6.
var NoProto = NoProto || {};
NoProto.Shape = (function(){
var thing = function(name){
var privateData = 'this is a ' + name;
var self = this;
this.base = function(){
return self;
};
this.doStuff = function(){
return privateData;
};
};
return thing;
})();
NoProto.Square = (function(){
var thing = function(colour){
NoProto.Shape.call(this, "square");
this.doStuff = function(){
// this fails (stack overflow)
// ------> how to call the "base" function: doStuff, and preserve the private data?
var val = this.base().doStuff();
return val + ', which is '+ colour;
};
};
thing.prototype = Object.create(NoProto.Shape.prototype);
return thing;
})();
Usage:
var noProtoSqr = new NoProto.Square('blue');
try {
alert(noProtoSqr.doStuff()); // ---> Stack Overflow!
} catch (e){
console.error('There was an error: ' + e);
}
For reference, this is how I got it working with prototypes:
var Proto = Proto || {};
Proto.Shape = (function(){
var thing = function(name){
this._pseudoPrivateData = 'this is a ' + name;
};
thing.prototype._pseudoPrivateData = '';
thing.prototype.doStuff = function(){
return this._pseudoPrivateData;
};
return thing;
})();
Proto.Square = (function(){
var thing = function(colour){
Proto.Shape.call(this, "square");
this._colour = colour;
};
thing.prototype = Object.create(Proto.Shape.prototype);
thing.prototype._colour = '';
thing.prototype.doStuff = function(){
var val = Proto.Shape.prototype.doStuff.call(this);
return val + ', which is '+ this._colour;
};
return thing;
})();
Usage:
var protoSqr = new Proto.Square('blue');
try {
alert(protoSqr.doStuff()); // --> "this is a square, which is blue"
} catch (e){
console.error('There was an error: ' + e);
}
When you use
NoProto.Shape.call(this, "square")
this assigns the Shape's doStuff to the current instantiation, if that's what you want. So, now this.doStuff will reference the original doStuff function from NoProto.shape. If you want to overwrite the doStuff function on the current instantiation while being able to call the original doStuff, save a reference to the old doStuff before assigning to this.doStuff:
var thing = function(colour){
NoProto.Shape.call(this, "square");
const oldDoStuff = this.doStuff;
this.doStuff = function(){
var val = oldDoStuff();
return val + ', which is '+ colour;
};
};
Live snippet:
var NoProto = NoProto || {};
NoProto.Shape = (function(){
var thing = function(name){
var privateData = 'this is a ' + name;
var self = this;
this.base = function(){
return self;
};
this.doStuff = function(){
return privateData;
};
};
return thing;
})();
NoProto.Square = (function(){
var thing = function(colour){
NoProto.Shape.call(this, "square");
const oldDoStuff = this.doStuff;
this.doStuff = function(){
var val = oldDoStuff();
return val + ', which is '+ colour;
};
};
thing.prototype = Object.create(NoProto.Shape.prototype);
return thing;
})();
var noProtoSqr = new NoProto.Square('blue');
try {
console.log(noProtoSqr.doStuff()); // ---> Stack Overflow!
} catch (e){
console.error('There was an error: ' + e);
}

Can't have access to a variable using call in Javascript

I'm studying Javascript and learning how to use call. I created this script and I don't know why I can't have access to this variable Time.
var MyObject;
(function(MyObject) {
var Runner = (function() {
function Runner(time) {
this.time = time;
}
var myFunctionArray = [];
Runner.prototype.execute = function() {
myFunctionArray[0]();
}
Runner.prototype.newTest = function(index, execute) {
var test = function() {
return execute.call(this);
}
myFunctionArray.push(test);
}
return Runner;
})();
MyObject.Runner = Runner;
})(MyObject || (MyObject = {});
var myNewObj = new MyObject.Runner(1000); myNewObj.newTest('1', function() {
console.log(this.time) //output: undefined
});
So how can I get time value inside newTest function?
Issue is in newTest function
Runner.prototype.newTest = function(index, execute) {
var test = function() {
return execute.call(this);
}
myFunctionArray.push(test);
}
Here this is pointing to test and not Runner. You will have to save context in a variable and then set it in call.
Runner.prototype.newTest = function(index, execute) {
var self = this;
var test = function() {
return execute.call(self);
}
myFunctionArray.push(test);
}
.call + self
var MyObject;
(function(MyObject) {
var Runner = (function() {
function Runner(time) {
this.time = time;
}
var myFunctionArray = [];
Runner.prototype.execute = function() {
myFunctionArray[0]();
}
Runner.prototype.newTest = function(index, execute) {
var self = this;
var test = function() {
return execute.call(self);
}
myFunctionArray.push(test);
}
return Runner;
})();
MyObject.Runner = Runner;
})(MyObject || (MyObject = {}));
var myNewObj = new MyObject.Runner(1000);
myNewObj.newTest('1', function() {
console.log(this, this.time) //output: undefined
});
myNewObj.execute()
.bind
As commented, you can even use .bind
var MyObject;
(function(MyObject) {
var Runner = (function() {
function Runner(time) {
this.time = time;
}
var myFunctionArray = [];
Runner.prototype.execute = function() {
myFunctionArray[0]();
}
Runner.prototype.newTest = function(index, execute) {
myFunctionArray.push(execute.bind(this));
}
return Runner;
})();
MyObject.Runner = Runner;
})(MyObject || (MyObject = {}));
var myNewObj = new MyObject.Runner(1000);
myNewObj.newTest('1', function() {
console.log(this, this.time) //output: undefined
});
myNewObj.execute()
When you declare your Runner function, you've actually declared a function that takes no arguments that then itself declares a function called Runner that takes one argument.
Actually In this code snippet :
Runner.prototype.newTest = function(index, execute) {
var test = function() {
return execute.call(this);
}
myFunctionArray.push(test);
}
this will reference to test variable (as per constructor invocation pattern)
So, to pass right variable cache the value of this in another variable and then pass that to function.

JavaScript way to define variable

Hello I saw "this" (now I just simplified it) code on a website source.
The question is:
Why is this._position defined with m(p) instead of just p ?
does it have some logical explanation ?
var emptyFunction = function j() {};
emptyFunction.thatReturnsValue = function(j) {
return j;
};
var m = emptyFunction.thatReturnsValue;
function o(){
this._position = 'left';
}
o.prototype.setPosition = function(p) {
'use strict';
this._position = m(p);
return this;
};
o.prototype.getPosition = function(){
return this._position;
}
function calculatePosition(oInst){
var position;
//( do some math to figure out the best position)
position = 'right';
oInst.setPosition(position);
}
function realWork(){
var orientation = new o();
calculatePosition(orientation);
console.log(orientation.getPosition());
}
empty function is used for more things:
**
function h(j) {
return function() {
return j;
};
}
var emptyFunction = function j() {};
emptyFunction.thatReturns = h;
emptyFunction.thatReturnsFalse = h(false);
emptyFunction.thatReturnsTrue = h(true);
emptyFunction.thatReturnsNull = h(null);
emptyFunction.thatReturnsThis = function() {
return this;
};
emptyFunction.thatReturnsValue = function(j) {
return j;
};
**

JavaScript object inheritance issue

I'm a beginner with JavaScript Objects and Prototypes and trying to develop my first " multi-level inherited" JS Objects, an unexpected issue came up.
This is my code:
var Utils = function () {};
Utils.prototype = {
sayHelloGeneral: function(){
console.log('hello');
}
};
var FormTools = function () {
Utils.call(this);
this.fields = [];
};
FormTools.prototype = Object.create(Utils.prototype);
FormTools.prototype.constructor = FormTools;
FormTools.prototype.sayHelloForm= function (fields) {
console.log('hello form');
};
function GroupManager(value) {
FormTools.call(this);
this.val = typeof values === 'undefined' ? 1 : value;
};
GroupManager.prototype = Object.create(FormTools.prototype);
GroupManager.prototype.constructor = GroupManager;
GroupManager.prototype.helloGroupManager= function (givenValue) {
console.log('Hello group manager');
};
Why when I try to call the group manager, it prints only the sayHelloGeneral function?
var GM = new GroupManager;
GM.sayHelloGeneral(); //->ok
GM.helloGroupManager(); //--> ok
GM.sayHelloForm(); //->sayHelloForm is not a function
It seems to be working fine. See the snippet below
var Utils = function () {};
Utils.prototype = {
sayHelloGeneral: function(){
console.log('hello');
}
};
var FormTools = function () {
Utils.call(this);
this.fields = [];
};
FormTools.prototype = Object.create(Utils.prototype);
FormTools.prototype.constructor = FormTools;
FormTools.prototype.sayHelloForm= function (fields) {
console.log('hello form');
};
function GroupManager(value) {
FormTools.call(this);
this.val = typeof values === 'undefined' ? 1 : value;
};
GroupManager.prototype = Object.create(FormTools.prototype);
GroupManager.prototype.constructor = GroupManager;
GroupManager.prototype.helloGroupManager= function (givenValue) {
console.log('Hello group manager');
};
var GM = new GroupManager;
//GM.sayhello(); //->ok---> should be sayHelloGeneral()
GM.sayHelloGeneral();
GM.helloGroupManager(); //--> ok
GM.sayHelloForm(); //->Works fine too

How to change the properties with factory method in 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

Categories

Resources