Accessing a private method in javascript - javascript

The following is my javascript code for accessing a private method. But it is not working. I receive a TypeError: string is not a function message. Can anyone please help me?
Here is my code:
function Boy(firstName,lastName) {
this.fisrtName = firstName;
this.lastName = lastName ;
var ladyLove = "Angelina";
var returnLove = function() {
return ladyLove;
};
this.sayLoud = function(){
return returnLove();
};
}
var achilles = new Boy("Bradley","Pitt");
var sayNow = achilles.sayLoud();
console.log(sayNow());

sayLoud() returns Angelina - which is a String, not a function.
You probably just want to go for:
console.log(sayNow);

Instead of using a string as a function, you should use console.log(sayNow);
Explained:
var achilles = new Boy("Bradley","Pitt"); // Will create a new object
var sayNow = achilles.sayLoud(); // call sayLoud(), return string
console.log(sayNow); // output the string

try this
var achilles = new Boy("Bradley","Pitt");
var sayNow = achilles.sayLoud;
console.log(sayNow());

Related

Copy object functions and properties in new object by value not by reference - javascript

I want to copy the functions and properties of an object into new object. The old object should not effect by changing made in new Object.
Here is the object definition:
var Call = function() {
this.number="123";
}
Call.prototype.function1 = function() {
return this.number;
}
var callobj = new Call();
I can access function1 using callobj.function1().
What I have tried to copy it:
Javascript:
var newcallobj = Object.assign({}, callobj);
In this case, i am not able to access function1 but i can access number property directly.
JQUERY:
var newObj = jQuery.extend(true, {}, callobj); OR
var newObj = jQuery.extend({}, callobj);
In this case, i am able to access function1 and property but when i change number like that newObj.number="222". It also change the value of original object.
I know that there is couple of other posts. But all is not working for me. Please let me know if i am doing any thing wrong?
AFTER #gurvinder372 answer(I am updating question):
After #gurvinder372 answer. It is working for first level of property but if it has another object like i show below and i change the value of property of another object. Then it is effecting on original object also.
var ABC = function(){
this.number = "333";
}
var Call = function() {
this.number="123";
this.anotherobj = new ABC();
}
Call.prototype.function1 = function() {
return this.number;
}
var callobj = new Call();
var newcallobj = Object.create(callobj);
newcallobj.anotherobj.number= "123";
console.log(newcallobj.anotherobj.number);
console.log(callobj.anotherobj.number);
Output of both is 123. #gurvinder372. can you check th above code ?
Object.assign only copies the enumerable properties of an object.
Use Object.create instead of Object.assign
var newcallobj = Object.create(callobj);
var Call = function() {
this.number="123";
}
Call.prototype.function1 = function() {
return this.number;
}
var callobj = new Call();
var newcallobj = Object.create(callobj);
console.log(newcallobj.function1());
Ok. By the help of #gurvinder372. The following solution is working for me.
var ABC = function(){
this.number = "333";
}
var Call = function() {
this.number="123";
this.anotherobj = new ABC();
}
Call.prototype.function1 = function() {
return this.number;
}
var callobj = new Call();
var newcallobj = Object.create(callobj);
newcallobj.anotherobj = Object.create(callobj.anotherobj);
newcallobj.anotherobj.number= "123";
console.log(newcallobj.anotherobj.number);
console.log(callobj.anotherobj.number);
Please let me know if there is any better solution other than this?

How to assign regex to variable for later use on a string?

I currently have this:
var input = "some input";
var firstRegex = input.match(/[aeiou]/gi);
var secondRegex = /ee/.test(input);
So if the input variable is undefined, both regex's will stop the code from compiling in the browser.
Is there a way to assign the regex's to variables so that they can later be called on input?
For example, inside an object:
var checkStrings = {
firstRegex : match(/[aeiou]/gi),
secondRegex : /ee/,
}
// call on input
checkStrings.firstRegex(input);
This link from Mozilla goes into a little more detail about the RegExp object in js, but if you want to simply assign a regexp to a variable, you can just do:
var firstRegex = new RegExp(/[aeiou]/gi);
var secondRegex = new RegExp(/ee/);
Then you would call them the same way you do now.
if (input) {
var matches = input.match(firstRegex);
var passedTest = secondRegex.test(input);
}
You could obviously do this much easier in an object as #IIya suggested, but I thought I'd add some info about the RegExp object in js.
You can use predicates:
var checkStrings = {
checkFirstRegex = function(x) {
return x.match(/[aeiou]/gi);
},
checkSecondRegex = function(x) {
return /ee/.test(x);
}
};
// call on input
checkStrings.firstRegex(input);
With the ES6 arrow functions it becomes even shorter:
var checkStrings = {
checkFirstRegex = x=> x.match(/[aeiou]/gi),
checkSecondRegex = x => /ee/.test(x)
};

Is there any way to extend an native object for a single variable?

I wanna get the next functionality:
var newString = String;
newString.prototype.reverse = function () {
return this.split("").reverse().join("")
}
var a = 'hello';
var b = newString('hello');
a.reverse();//reverse is not a function
b.reverse();//olleh
try extend .prototype before add function and doesn't work, i don't even know if it is possible.
You could do the following:
var newString = function(initialVal) {
var val = new String(initialVal);
val.reverse = function () {
return this.split("").reverse().join("")
};
return val;
};
var a = 'hello';
var b = newString('hello');
a.reverse();//reverse is not a function
b.reverse();//olleh
It sounds like you're looking for:
String.prototype.reverse = function () {
return this.split("").reverse().join("")
}
var a = 'hello';
alert(a.reverse());
Note that extending built in objects like "String" is highly controversial at best.

Function method in object in Javascript

I am working on a Javascript object exercise. My output is not what I expected. Please take a look at my code and give some advise. Here is the code:
function myFunction(name) {
this.name = name;
this.models = new Array();
this.add = function (brand){
this.models = brand;
};
}
var c = new myFunction ("pc");
c.add("HP");
c.add("DELL");
console.log(c.models);
The output is "DELL"
My expected output is ["HP","DELL"]
Thank you so much for your help!
Change the add function. You want to push the brand into the model. Not set the model to it.
this.add = function (brand){
this.models.push(brand);
};
To add something to an array, you should use the .push() method.
Change your code to:
function myFunction(name) {
this.name = name;
this.models = new Array();
this.add = function (brand){
this.models.push(brand);
};
}
P.S. It is customary to name such constructor type of functions starting with a capital letter.

Why is my javascript object empty after constructing it

I use Knockout.js, and I have an object called letter in my script. That code looks as follows:
function letter(filePath, imagePath, countryId) {
self.filePath = filePath;
self.imagePath = imagePath;
self.countryId = countryId;
}
Then, another place in my code, the following snippet runs:
var uploadedLetter = new letter(data.key,'',59);
viewModel.letters.push(uploadedLetter);
I know that my data.key is a normal string value.
My viewModel code is like this:
var SendWindowedLetterViewModel = function(formSelector, data) {
var self = this;
self.letters = ko.observableArray([]);
}
Applying bindings on my view:
var createLetterData = {
};
var viewModel = new SendWindowedLetterViewModel('#sendLetterForm', createLetterData);
ko.applyBindings(viewModel, document.getElementById('sendLetterForm'));
However, when I look in FireBug after this line has been run, I have the following output:
And I cannot access any of my properties, and if I lookup the object in FireBug, it seems to be 100% empty.
Probably the most simple question ever asked on StackOverflow, but what am I overlooking here?
In letter, you use self.filePath = filePath.
But self isn't defined anywhere in its scope.
So you either do
function letter(filePath, imagePath, countryId) {
var self = this;
self.filePath = filePath;
self.imagePath = imagePath;
self.countryId = countryId;
}
or directly
function letter(filePath, imagePath, countryId) {
this.filePath = filePath;
this.imagePath = imagePath;
this.countryId = countryId;
}

Categories

Resources