How to span a variable to a class in javascript

I am trying to create a class using the foo {} class syntax and want a private variable inside it. Right now I have something like this:

'use strict';
class foo {
  constructor(x1,y1) {
    var x = x1;
    var y = y1;
  }
  get x() {
    return x;
  }
  get y() {
    return y;
  }
}

      

Whenever I try to access the files foo.x and foo.y, I get x not found error. However, when I tried to put variable declarations outside of the constructor, it stopped working. I also use static methods, so I can't get away with the class syntax without doing some work. How can I fix this? How can I declare a variable inside an object that is global and cannot be found outside?

+3


source to share


3 answers


These getters are declared on the prototype where they cannot access the private (copied) variables in the constructor. You will need to use Object.defineProperty

to create instances specific to instances:

class Foo {
  constructor(x, y) {
    Object.defineProperties(this, {
      x: {get() { return x; }, configurable: true},
      y: {get() { return y; }, configurable: true}
    });
  }
}

      



This is no different from ES5. Btw if you don't assign variables you can also make them unwritable properties.

+4


source


Okay, people are assuming you want to use getters and setters. If it doesn't, this will be enough:



'use strict';
class foo {
  constructor(x1,y1) {
    this.x = x1;
    this.y = y1;
  }
}

var f = new foo(10, 20);

console.log(f.x)
console.log(f.y)
      

Run codeHide result


JSFiddle: https://jsfiddle.net/gLxnqfrv/

+1


source


Taken from es6-features , this is the correct syntax for the class as well as its getters and setters.

class Rectangle {
    constructor (width, height) {
        this._width  = width
        this._height = height
    }
    set width  (width)  { this._width = width               }
    get width  ()       { return this._width                }
    set height (height) { this._height = height             }
    get height ()       { return this._height               }
    get area   ()       { return this._width * this._height }
}
var r = new Rectangle(50, 20)
r.area === 1000

      

It's important to note that there is no prototype damage requirement in ES6.

0


source







All Articles