Here is my code:
jack = {
name: 'Jack',
birthYear: 1992,
calcAge: function () {
this.age = 2021 - this.birthYear;
return this.age;
}
};
console.log(jack.age);
Calling 'jack.age' returns 'undefined' in the console. Why is it not returning the result of the
expression in the function?
As mentioned by #Pointy you have not defined the age property in your object, for that you have created a function called calcAge if you don't call it then the property would be undefined which is what is returned.
If you call the calcAge function then age property would be defined and you can access it through the object.
You don't need to return age property from calcAge you can directly access it from the object if you want to recalculate the age property again then you can again call the calcAge function.
jack = {
name: 'Jack',
birthYear: 1992,
calcAge: function () {
this.age = 2021 - this.birthYear;
}
};
jack.calcAge();
console.log(jack.age);
Related
const meDetails = {
firstName: 'arman',
lastName: 'soltani',
birthday: 1991,
hasDriverLicense: true,
calcAge: function () {
this.age = 2037 - this.birthday;
return this.age;
}
};
console.log(meDetails.age);
why the age is not defined??
the variable of named 'age' is not initialized before calling calcAge.
at first you should call calcAge to init meDetailes.age variable at runtime
then meDetails.age is valued and you can use it
You need to call calcAge() first to set the age property
meDetails.calcAge();
console.log(meDetails.age);
But you probably want a getter for age.
const meDetails = {
firstName: 'arman',
lastName: 'soltani',
birthday: 1991,
hasDriverLicense: true,
get age() {
return 2037 - this.birthday;
}
};
console.log(meDetails.age);
I'm trying to understand the use of "this". I can't get the age from the function calculation(undefined). What am I doing wrong?
const reina= {
firstName: 'Reina',
birthYear: 1998,
location:'Tokyo',
friends:['Chihomi','Lei','Louis'],
calcAge: function(){
this.age= 2021 - this.birthYear;
return this.age;
}
}
console.log(reina.age);
output:
undefined
You never called the calcAge function.
const reina = {
firstName: 'Reina',
birthYear: 1998,
location: 'Tokyo',
friends: ['Chihomi', 'Lei', 'Louis'],
calcAge: function() {
this.age = 2021 - this.birthYear;
return this.age;
}
}
console.log(reina.calcAge());
console.log(reina.age);
It seems like a getter is most appropriate in this case.
const reina = {
firstName: 'Reina',
birthYear: 1998,
location: 'Tokyo',
friends: ['Chihomi', 'Lei', 'Louis'],
get age() {
return 2021 - this.birthYear;
}
}
console.log(reina.age);
For the sake of reusability, I would use a Class instead of assigning to an object. That would leave less code in the long run.
this points to the current scope you're in, whether your in a method, an object or a class.
To create a class, you need to add a constructor, that you can send in parameters to. As you can see in the code, this in the constructor means the class Person when I call calcAge().
I also added new Date().getFullYear() which should be self-explanatory.
class Person {
constructor(firstName, birthYear, location, friends) {
this.firstName = firstName;
this.birthYear = birthYear;
this.location = location;
this.friends = friends;
this.age = this.calcAge(birthYear);
}
calcAge(birthYear) {
return new Date().getFullYear() - birthYear;
}
}
const reina = new Person('Reina', 1998, 'Tokyo', ['Chihomi', 'Lei', 'Louis']);
const rickard = new Person('Rickard', 1890, 'Stockholm', ['Beatrice', 'Gretchen', 'Hans']);
console.log(reina.firstName, reina.age);
console.log(rickard.firstName, rickard.age);
I accidentally missing this keyword inside setter, getter methods. It leads to some weird bugs: (tested with Chrome, Firefox)
Case 1:
let user = {
name: "John",
set fullName(value) {
name = value;
},
get fullName() {
return name;
}
};
user.fullName // ""
user.fullName = "Batman"
user.fullName // "Batman"
user.name // "John"
Why is property name still "John" ? Where did "Batman" come from?
Case 2: change variable name of the above code, something happens:
let user = {
anythingButName: "John",
set fullName(value) {
anythingButName = value;
},
get fullName() {
return anythingButName;
}
user.fullName // anythingButName is not defined at Object.get fullName [as fullName]...
};
Can't use any name but the word name for the variable in above code. I don't know why?
Both cases are equal. What happens:
let user = {
name: "John",
set fullName(value) {
name = value;//sets window.name to *value*
},
get fullName() {
return name;//returns window.name
}
};
console.log(
user.fullName,// window.name is "" by default
window.name,
user.fullName = "Batman", //=> window.name
window.name,
user.fullName, // "Batman" ==window.name
user.name // "John" //what you really wanted
);
It works ( not really ) just with name as window.name is a default property and therefore set to "" at the beginning.
You can check in your second case:
console.log(
user.fullName, // undefined yet
user.fullName="test",
user.fullName // test
);
I have recently started to learn JavaScript and would like to know if it is possible to use a object variable in a function directly within the same object. Here is my code so far.
var user = {
name: 'Example',
age: 687,
address: {
firstLine: '20',
secondLine: 'St Fake',
thirdLine: 'Fakeland'
},
logName: function(inputName, inputAge){
console.log(user.name);
console.log(user.age);
console.log(inputAge);
console.log(inputName);
}
};
user.logName('Richard', 20);
How is it possible to link to the name and age variables of user in the function without needing to prefix the object name onto the variable?
In most cases, you can just use the this keyword to get the object on which your function was called as a method upon. In your example:
var user = {
name: 'Example',
age: 687,
address: {
firstLine: '20',
secondLine: 'St Fake',
thirdLine: 'Fakeland'
},
logName: function(inputName, inputAge) {
console.log(this.name);
// ^^^^
console.log(this.age);
// ^^^^
console.log(inputAge);
console.log(inputName);
}
};
user.logName('Richard', 20); // method call on `user`,
// so `this` will become the `user` in the function
Welcome to the "this" key word!
Just reference it by this.value
You can use the this keyword . You can better understand this keyword using this article
The code will be like this
var user = {
name: 'Example',
age: 687,
address: {
firstLine: '20',
secondLine: 'St Fake',
thirdLine: 'Fakeland'
},
logName: function (inputName, inputAge) {
console.log(this.name);
console.log(this.age);
console.log(inputAge);
console.log(inputName);
}
};
user.logName('Richard', 20);
I'm writing an app in node and I am running into something strange.
I pass an object into a function with the call() method to modify that object. When inside the function when I do console.log(this) it returns the object fine, however when I try to do console.log(this.foo) or try to modify the object it says undefined. UPDATE: I also have to mention I pass this function in an object because I have to inject the functions in to another function. (more specific, I'm trying to get this to work. Maybe that is also part of the problem.
var obj = {name: "John", age: 23};
var functions = {up: function() { /* do stuff */ }, down: function() { /* do stuff */
functions.up.call(obj);
up: function() {
console.log(this); //returns {name: "John", age: 23}
console.log(this.name); //returns undefined
this.wife = "Jenny"; //doesn't do anything
}
However if I set properties with an '_' they do exist but don't show up when I call console.log(this);
up: function() {
this._wife = "Jenny"; //doesn't do anything
console.log(this._wife); //returns "Jenny"
console.log(this); //still returns {name: "John", age: 23}
}
I've tried everything like using this.set(key, value), this.get(key), this.attributes["name"].value,..
Maybe I'm misunderstanding how 'this' works, but after hours of searching and trying things I'm clueless..
When trying your code in the console I fixed the syntax to a function expression and it works for me, perhaps this was your problem?
var obj = {name: "John", age: 23};
up.call(obj);
function up() {
console.log(this); //returns {name: "John", age: 23}
console.log(this.name); //returns "John"
this.wife = "Jenny"; // works
console.log(this);
}
I'm getting working output from this in node, chrome/win7 & notepad++ plugin :
var obj = { name: "John", age: 23 };
var functions = {
up: function() {
console.log(this); //returns {name: "John", age: 23}
console.log(this.name); //returns undefined
this.wife = "Jenny"; }, //doesn't do anything
down: function(){ } }
functions.up.call(obj);
console.log('obj:',obj);
output :
{ name: 'John', age: 23 }
John
obj: { name: 'John', age: 23, wife: 'Jenny' }
Your understanding of 'this' seems correct
you could try replacing
functions.up.call(obj);
with
temp = obj.up;
obj.up = functions.up;
obj.up();
obj.up = temp;//or: delete obj.up;
I had the same problem. Finally I found solution - I put the problematic code in round brackets:
var i = node.declarations.length; //Error: cannot get length of undefined
var i = (node.declarations).length; // 11
I guess you should do something like that:
console.log((this.name).toString());
or
console.log((this.name));