am a beginner learning javascript and was playing around with Objects and am wondering why this code is throwing an error.
var a = {
greeting: "Hello",
greet: this.greeting + "John"
}
console.log(a.greet);
am a beginner learning javascript and was playing around with Objects and am wondering why this code is throwing an error.
var a = {
greeting: "Hello",
greet: this.greeting + "John"
}
console.log(a.greet);
While it's been clarified why your code throws an error, I wanted to explain how you could have it instead.
Javascript makes no difference between ordinary functions and constructors, to a class is just a call to new function
with any function in front of it.
Therefore, a way the object can reference itself is by using a function body as its definition:
const AClass = function () {
this.greeting = 'Hello'
this.greet = this.greeting + ' John'
}
const a = new AClass()
console.log(a.greet)
Shorthand since you aren't going to create more than one AClass
object (at least in your example):
const a = new function () {
this.greeting = 'Hello'
this.greet = this.greeting + ' John'
}()
console.log(a.greet)
Yours doesn't work because of the problems described in the comments.
I'm guessing that you want something like this:
var a = {
greeting: "Hello",
greet: function() {return this.greeting + " John"}
}
console.log(a.greet());
Or like this:
var a = (() => {
var greeting = "Hello"
return {
greeting,
greet: greeting + ' John'
}
})()
console.log(a.greet);
The first one makes greet
a function, which means that it will respond to later changes in greeting
. The second one creates an object based on the greeting
value. But you have to use a local variable for the reference, since your this
at the time of construction is not the new object but some outer scope, possibly something like window
.
This question you have is explained here: How Do I reference objects proerty at creation
In order to do what you want you can use an object getter.
var b = {
greeting: "Hello",
get greet() { //this a getter that accesses greeting
return this.greeting + " John";
}
}
console.log(b.greet);