Method error: Method name not defined [duplicate] - javascript

This question already has answers here:
Javascript: Do I need to put this.var for every variable in an object?
(6 answers)
Closed 7 years ago.
Why isn't this code working? I'm trying to use the method to add up the properties and then assign the added up properties to its own value.
function howLongILivedSomewhere(college, home1, home2) {
this.birthHome = 18;
this.college = college;
this.home1 = home1;
this.home2 = home2;
this.calcYearsAlive = function() {
return birthHome + college + home1 +home2;
};
this.yearsAlive = calcYearsAlive();
}
var me = new howLongILivedSomewhere(4, 2, 3);
console.log(me);

You missed this keyword during your method / property call. Try like below.
function howLongILivedSomewhere(college, home1, home2) {
this.birthHome = 18;
this.college = college;
this.home1 = home1;
this.home2 = home2;
this.calcYearsAlive = function() {
return this.birthHome + this.college + this.home1 + this.home2;
};
this.yearsAlive = this.calcYearsAlive();
}
var me = new howLongILivedSomewhere(4, 2, 3);
console.log(me.yearsAlive); // output: 27
What is this keyword?
A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
How does "this" keyword work within a function?

Update the constructor to:
function howLongILivedSomewhere(college, home1, home2) {
this.birthHome = 18;
this.college = college;
this.home1 = home1;
this.home2 = home2;
this.calcYearsAlive = function() {
return this.birthHome + this.college + this.home1 + this.home2;
};
this.yearsAlive = this.calcYearsAlive();
}
var me = new howLongILivedSomewhere(4, 2, 3);
console.log(me);
Use this keyword when you need to access the object properties (see here more details).

Related

Is there a way to call a function through using a string that matches its name? [duplicate]

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 2 years ago.
This is what I have attempted, and may give a better gist of the question I'm trying to ask:
var x = "run";
var y = "Function";
var xy = x + y;
function runFunction() {
console.log("Function has been called.");
}
xy();
What am I doing wrong here?
You could use eval(), but don't. Instead, store your functions in an object:
const functions = {
greetingOne: () => console.log("Hello!"),
anotherGreeting: () => console.log("Hi there!");
};
const f = "greetingOne";
functions[f]();
It is possible if the function lives on an object.
const obj = {
runFunction: function() {console.log('hello')}
}
var x = "run";
var y = "Function";
var xy = x + y;
obj[xy]();
You can call eval that run string as Javascript code
function runFunction() {
console.log("Function has been called.");
}
functionName = 'runFunction'
eval(functionName + '()');
All global functions stores in window object.
let first = "first";
let second = "Second";
let xy = first+second;
function firstSecond() {
return "Hello World";
}
console.log(window[xy]());

Overwrite anonymous const function in javascript [duplicate]

This question already has answers here:
delete or override const variables in javascript Harmony / ECMAScript 6
(2 answers)
Closed 3 years ago.
I was trying to figure this out with a friend.
Let's say you have a function like this:
const foo = function(i) { return function(j){ return 2 * j } };
How would I override foo with a different method?
Let's say I want to reuse foo with a different anonymous function that does something like function(j){ return 3 * j; };
How would I do that?
EDIT: I saw this post, but that's for variables. I'm asking specifically about anonymous methods.
EDIT 2: This is a proof of concept, so let's say that foo is a const and I can't turn it into a let
const is used for constants, so it's not for overriding.
If you want to override your variable, use let or var
const constantFunction = x => x + 1;
let variableFunction = x => x + 2;
try {
variableFunction = x => x + 3;
console.log('Re-assigning to a variable: DONE');
} catch(e) {
console.log('Error while re-assigning to a variable');
}
try {
constantFunction = x => x + 3;
console.log('Re-assigning to a constant: DONE');
} catch(e) {
console.log('Error while re-assigning to a constant');
}

The 'this' context is lost during assignment, but not quite? [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 5 years ago.
In the following example there is a simple object. Two instances were created for me to test variable scope.
When test1a (and test2a) is assigned to the method ShowNum it behaves identically as when calling oneObj.ShowNum() by itself. However, when test1b is assigned to the method ShowNum2, then it behaves differently than calling oneObj.ShowNum2() directly.
This is a little puzzling to me because it seems that the 'this' scope is being lost during assignment, but at the same time it is NOT lost because 'num' is still found (and num is as unique to the object instance as this.num2 is).
What is the esoteric explanation for this behavior ?
function TestObject ()
{
var num = 25;
this.num2 = 50;
this.ShowNum = function () {return num;}
this.ShowNum2 = function () {return this.num2;}
this.SetNum = function (newnum) {num = newnum;}
}
var oneObj = new TestObject();
var twoObj = new TestObject(); twoObj.SetNum(100); twoObj.num2 = -12;
var test1a = oneObj.ShowNum;
var test1b = oneObj.ShowNum2;
var test2a = twoObj.ShowNum;
var test2b = twoObj.ShowNum2;
console.log(oneObj.ShowNum());
console.log(oneObj.ShowNum2());
console.log(test1a());
console.log(test1b());
console.log(twoObj.ShowNum());
console.log(twoObj.ShowNum2());
console.log(test2a());
console.log(test2b());
Result:
25
50
25
undefined
100
-12
100
undefined
EDIT:
This question does seem like a variant of the one -->here as pointed out by the replies.
My instinctive expectation was that var test1b = oneObj.ShowNum; should imply
var test1b = oneObj.ShowNum2.bind(oneObj); making it for consistent behavior across languages (as Mahesha999 mentioned with the following)
The this keyword behaves differently in JavaScript compared to other
language. In Object Oriented languages, the this keyword refers to the
current instance of the class. In JavaScript the value of this is
determined mostly by the invocation context of function
(context.function()) and where it is called.
Right now I don't feel like pressing further and I consider this matter closed.
Reason :
// you are not assigning the whole object , but just passing refernce to the function
var test1a = oneObj.ShowNum;
var test1b = oneObj.ShowNum2; // so from here it will lose the context of this
test1a is like
function () {return num;}
and test1b is like
function () {return this.num2;}
Here, if you directly assign the function, here this is not pointing to parent function anymore. as you have just assigned the function
You can check that by just putting console.log inside like,
this.ShowNum2 = function () { console.log(this); return this.num2;}
Debugging : Run the below code snippet and you will get idea :
function TestObject ()
{
var num = 25;
this.num2 = 50;
this.ShowNum = function () {return num;}
this.ShowNum2 = function () { console.log(this); return this.num2;}
this.SetNum = function (newnum) {num = newnum;}
}
var oneObj = new TestObject();
var twoObj = new TestObject(); twoObj.SetNum(100); twoObj.num2 = -12;
var test1a = oneObj.ShowNum;
var test1b = oneObj.ShowNum2;
var test2a = twoObj.ShowNum;
var test2b = twoObj.ShowNum2;
console.log(oneObj.ShowNum());
console.log(oneObj.ShowNum2());
console.log(test1a());
console.log(test1b());
console.log(twoObj.ShowNum());
console.log(twoObj.ShowNum2());
console.log(test2a());
console.log(test2b());
Solution :
//.bind(parent_object);
var test1b = oneObj.ShowNum2.bind(oneObj);
var test2b = twoObj.ShowNum2.bind(twoObj);
function TestObject ()
{
var num = 25;
this.num2 = 50;
this.ShowNum = function () {return num;}
this.ShowNum2 = function () {return this.num2;}
this.SetNum = function (newnum) {num = newnum;}
}
var oneObj = new TestObject();
var twoObj = new TestObject(); twoObj.SetNum(100); twoObj.num2 = -12;
var test1a = oneObj.ShowNum;
var test1b = oneObj.ShowNum2.bind(oneObj);
var test2a = twoObj.ShowNum;
var test2b = twoObj.ShowNum2.bind(twoObj);
console.log(oneObj.ShowNum());
console.log(oneObj.ShowNum2());
console.log(test1a());
console.log(test1b());
console.log(twoObj.ShowNum());
console.log(twoObj.ShowNum2());
console.log(test2a());
console.log(test2b());

how to declare object with recursive properties? in nodejs [duplicate]

This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 5 years ago.
I am declaring:
var ENV = {
VERSION: 1,
SERVER: 'midomain.com',
SERVER_DEV: 'testdomain.dev',
API_ROUTE: 'socket/',
API: (false) ? this.SERVER + '/' + this.API_ROUTE : this.SERVER_DEV + '/' + this.API_ROUTE };
should get:
{ VERSION: 1,SERVER: 'midomain.com',SERVER_DEV: 'testdomain.dev',API_ROUTE: 'socket/', API: 'testdomain.dev/socket/' }
but I get
{ VERSION: 1,SERVER: 'midomain.com',SERVER_DEV: 'testdomain.dev',API_ROUTE: 'socket/', API: 'undefined/undefined' }
Because in that case context is global, not an your object. You can check it with an example:
window.b = 666;
let a = {
prop: this.b
}
console.log(a); // display: {prop: 666}
You can fill your object properties one-by-one
let ENV = {};
ENV.VERSION = 1;
ENV.SERVER = 'midomain.com';
ENV.API = ENV.SERVER;
or create function with 'new' syntax
var ENV = new function() {
this.VERSION = 1;
this.SERVER = 'midomain.com';
this.API = this.SERVER;
};

Objects, prototypal inheritance, and a failing function [duplicate]

This question already has answers here:
How to call a function in Javascript [duplicate]
(4 answers)
Closed 5 years ago.
While trying to move on to some intermediate/advanced Javascript concepts, I've run into a problem. In the following code, the object prototype and created objects seem to be functioning fine. But when I try to then use them in the function 'winner', the result always declares the winner as the second argument passed, regardless of their score. Here, Mike has a higher score(395) than Peter (206) and should be declared the winner. Also, the console is logging the message "Peter wins with a score of function () {
return (this.age * 5) + this.height;
}".
Any help understanding what I'm doing wrong would be greatly appreciated.
var player = {
name: 'Default',
age: 'Default',
height: 'Default',
score: function() {
return (this.age * 5) + this.height;
}
}
var Mike = Object.create(player);
Mike.name = 'Mike';
Mike.age = 67;
Mike.height = 60;
var Peter = Object.create(player);
Peter.name = 'Peter';
Peter.age = 30;
Peter.height = 56;
var winner = function(player1, player2) {
var player1score = player1.score;
var player2score = player2.score;
if(player1score > player2score) {
console.log(player1.name + ' wins with a score of ' + player1.score);
} else {
console.log(player2.name + ' wins with a score of ' + player2.score);
}
}
winner(Mike, Peter);
winner(Peter, Mike);
Replace
var player1score = player1.score;
var player2score = player2.score;
with
var player1score = player1.score();
var player2score = player2.score();
You have to call the function, if you just write player1.score you will get the body of the function.

Categories