class - Instance Variables in Javascript Classes -
i code in php , java, work on front end of project , use javascript. create objects differently below, came across , caught interest being syntax similar program in.
i poking around, trying figure out how use instance variables in javascript classes using syntax below. i've tried declaring instance variables name;, or _name;, or var name;, or of previous variables , adding = null;, still errors in console. errors my-file.js:2 uncaught syntaxerror: unexpected identifier. i'm trying set instance variable through constructor.
how use instance variables in javascript, using syntax below?
class myclass { var _name; constructor(name) { _name = name; alert("hello world, 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); }
this still proposal , follows:
class { property = "value"; } btw, when want access class property (i.e. own object property) you'll still need use this.property:
class { property = "value"; constructor() { console.log(this.property); } } if want use syntax today, you'll need use transpiler babel.
Comments
Post a Comment