Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

javascript - Declare a class property outside of a class method

See how x and y are declared in constructor:

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}

is there an way to declare properties outside of functions for instance:

class Point {
  // Declare static class property here
  // a: 22
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}

So I want to assign a to 22 but I am unsure if i can do it outside the constructor but still inside the class..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Initializing properties directly on a class in ES6 is not possible, only methods can currently be declared in this way. Same rules stand in ES7 as well.

However, it is a proposed feature that might come after ES7 (currently in stage 3). Here is the official proposal.

Additionally, the syntax the proposal is suggesting is slightly different (= instead of :):

class Point {
  // Declare class property
  a = 22
  // Declare class static property
  static b = 33
}

If you are using Babel, you can use the stage 3 settings to enable this feature.

Here's a Babel REPL example


The other way to do this in ES6, other than in the constructor, is to do it after the class definition:

class Point {
  // ...
}

// Declare class property
Point.prototype.a = 22;

// Declare class static property
Point.b = 33;

Here's a good SO Thread diving into this topic some more


Note:

As Bergi mentioned in the comments, the suggested syntax:

class Point {
  // Declare class property
  a = 22
}

is just syntactic sugar to provide a shortcut for this code:

class Point {
  constructor() {
    this.a = 22;
  }
}

Where both of those statements assign a property to an instance.

However, this isn't exactly the same as assigning to the prototype:

class Point {
  constructor() {
    this.a = 22;  // this becomes a property directly on the instance
  }
}

Point.prototype.b = 33; // this becomes a property on the prototype

Both would still be available via an instance:

var point = new Point();
p.a // 22
p.b // 33

But getting b would require going up the prototype chain while a is available directly on the object.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...