I mostly code in PHP and Java, but I will occasionally work on the front end of a project and use JavaScript. I usually create objects differently than below, but I came across this and it caught my interest being that the syntax is similar to what I usually program in.
I was poking around, trying to figure out how to use instance variables in JavaScript classes using the syntax below. I've tried declaring the instance variables by name;
, or _name;
, or var name;
, or all of those previous variables and adding = null;
, but still get errors in my console. The errors are mostly my-file.js:2 Uncaught SyntaxError: Unexpected identifier
. I'm just trying to set my instance variable through my constructor.
How do I use instance variables in JavaScript, using the syntax below?
class MyClass {
var _name;
constructor(name) {
_name = name;
alert("Hello world, from OO JS!");
this.myFunction();
}
myFunction() {
document.getElementById("myElement").addEventListener("click", function() {
console.log("Ant's function runs. Hello!");
});
}
}
window.onload = function() {
var person = "John Smith";
var myClass = new MyClass(person);
}
An instance variable is just a property of an object, as Felix Kling said. You can't use props because that's referencing a global or local variable called props . What you want to access is the current value of props for the current component, stored in this.
Class methods can access class variables and class methods directly. Class methods cannot access instance variables or instance methods directly—they must use an object reference.
An instance variable is a variable which is declared in a class but outside of constructors, methods, or blocks. Instance variables are created when an object is instantiated, and are accessible to all the constructors, methods, or blocks in the class. Access modifiers can be given to the instance variable.
An instance is an object containing data and behavior described by the class. The new operator instantiates the class in JavaScript: instance = new Class() . For example, you can instantiate the User class using the new operator: const myUser = new User(); new User() creates an instance of the User class.
This is still a proposal and it would look as follows:
class A {
property = "value";
}
BTW, when you want to access a class property (i.e. an own object property) you'll still need to use this.property
:
class A {
property = "value";
constructor() {
console.log(this.property);
}
}
If you want to use this syntax today, you'll need to use a transpiler like Babel.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With