1

I want to create simple plugin with ES6 using classes . but without using new keyword . it possible to return new instance from class automatically .

example :

class Rectangle{
    constructor(x, y){
        this.x = x,
        this.y = y
    }

    eq(){
        console.log('Result ' + this.x * this.y )
    }

}

const myRect = new Rectangle(10, 10);
myRect.eq();

I want to use like this

Rectangle.eq(10, 10);
2
  • 1
    Why use classes if you don't seem to need them? Classes are probably not the right solution to your problem. You could add a static method like static eq(x, y) { return new this(x, y).eq(); } to achieve what you want, but unless there is more to it than you are showing, a class is unnecessary. Commented May 5, 2017 at 18:12
  • I think the question is... is there a way to turn "eq()" into a class method instead of an instance method but that doesn't make any sense with "this" in the definition. Commented May 5, 2017 at 18:13

3 Answers 3

1

Define eq() as a static method. Then you don't have to instantiate your class, but can use it directly.

Sign up to request clarification or add additional context in comments.

6 Comments

it working but Should not be used 'this' keyword inside a function
Yes, because this refers to the instance of the class. When you're using a static method, you don't have an instance.
Thank you . but i have problem with call function inside another function jsfiddle.net/ceuyxqbg Uncaught TypeError: this.msg is not a function
@ИскренХаджинедев: That's not completely correct. What this refers to depends on how a function is called. If a static method is called as Foo.bar(), then this inside bar will refer to Foo, i.e. the class/constructor function itself.
@FelixKling Can you send me basic template for create javascript plugin with option
|
1

You can use module design pattern.

var Rectangle = (function() {
  return {
    eq: function(x, y) {
      console.log(x * y);
    }
  };
})();

Rectangle.eq(2,5); 

Check here for reference : https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know

1 Comment

In this case, even if you remove construct it will still work : jsfiddle.net/dhgp1jwp/1
0

Reflect.construct does the same thing:

class Rectangle{
    constructor(x, y){
        this.x = x,
        this.y = y
    }

    eq(){
        console.log('Result ' + this.x * this.y )
    }

}

Reflect.construct(Rectangle, [10, 10]).eq();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.