Javascript get method class

Get methods of class in JavaScript

When in context of a static method or getter there is no «current instance» by intention and so is available to refer to the definition of current class directly. is not referring to some instance either, but to static methods and getters written in context of some class current one is extending. is basically referring to same instance, but somewhat addressing methods and getters written in context of some class current one is extending (by using the prototype of Foo’s prototype).

Get methods of class in JavaScript

How to get list of methods defined for a class in js?

class c < methodA()<>static methodB()<> log() static logStatic() > 

You can use Object.getOwnPropertyNames and filter the instance and static methods:

class c < methodA()<>static methodB()<> log() static logStatic() > const instanceOnly = Object.getOwnPropertyNames(c.prototype) .filter(prop => prop != "constructor"); console.log(instanceOnly); const staticOnly = Object.getOwnPropertyNames(c) .filter(prop => typeof c[prop] === "function"); console.log(staticOnly);

How do I get a list of static methods inside a javascript, Find centralized, trusted content and collaborate around the technologies you use most. Learn more

How do I get a list of static methods inside a javascript class [duplicate]

I would like to get a list of methods from a class that are static.

class Person < constructor()< let x = this.getStaticMethods(); // how?? - would return [Person.Emails] >static Emails() < // returns emails >> 

I need the function itself (bound or unbound) not just the name. How would I get these?

class Person < constructor()< let staticMethods = Object.create(null); for(var attr in Person) < if(typeof Person[attr] === 'function') < staticMethods[attr] = Person[attr]; >> console.log(staticMethods); > static Emails() < // returns emails >> const p = new Person(); 

You should probably add hasOwnProperty to the final version, but this will get you most of the way there. http://codepen.io/anon/pen/BjeMEd

Javascript — JS call static method from class, The introduction of the «class» keyword to the language does not alter the fundamental nature of JavaScript’s prototype-based classes. Static methods. Static methods are defined as properties of the constructor function rather than properties of the prototype object.

How do you get a static reference to a method of a class in JavaScript?

Say I want to pass around a reference to a method of a class in JavaScript:

class Example < constructor() < this.field = "value" >exampleMethod() < console.log(this.field) >exampleMethod2() < this.field += "." >> // get references to the methods without having an instance of the object (important detail) let methods = [Example.exampleMethod, Example.exampleMethod2] // not correct let sampledMethod = methods[Math.floor(Math.random()*methods.length)] let object = new Example() object.sampledMethod() 

Weird example, but say I have more legitimate reasons for wanting these references without an instance of the object. Is there a clean way to do so?

The methods exist on the object’s prototype . To call a detached method on an object instance, use .call or .apply :

class Example < constructor() < this.field = "value" >exampleMethod() < console.log(this.field) >exampleMethod2() < this.field += "." >> let methods = [Example.prototype.exampleMethod, Example.prototype.exampleMethod2]; let sampledMethod = methods[Math.floor(Math.random() * methods.length)]; let object = new Example(); console.log(object); console.log('Calling', sampledMethod); sampledMethod.call(object); console.log(object);

Javascript — ES6 — Call static method within a class, If you are calling the static function from inside an instance, the right way to refer to the static function of the class is: this.constructor.functionName (); Call static methods from regular ES6 class methods. Share. Improve this answer. edited Mar 14, 2021 at 15:24. Saksham. 8,765 6 42 69.

Call static methods from regular ES6 class methods

What’s the standard way to call static method s? I can think of using constructor or using the name of the class itself, I don’t like the latter since it doesn’t feel necessary. Is the former the recommended way, or is there something else?

Here’s a (contrived) example:

class SomeObject < constructor(n)< this.n = n; >static print(n) < console.log(n); >printN() < this.constructor.print(this.n); >> 

Both ways are viable, but they do different things when it comes to inheritance with an overridden static method. Choose the one whose behavior you expect:

class Super < static whoami() < return "Super"; >lognameA() < console.log(Super.whoami()); >lognameB() < console.log(this.constructor.whoami()); >> class Sub extends Super < static whoami() < return "Sub"; >> new Sub().lognameA(); // Super new Sub().lognameB(); // Sub 

Referring to the static property via the class will be actually static and constantly give the same value. Using this.constructor instead will use dynamic dispatch and refer to the class of the current instance, where the static property might have the inherited value but could also be overridden.

This matches the behavior of Python, where you can choose to refer to static properties either via the class name or the instance self .

If you expect static properties not to be overridden (and always refer to the one of the current class), like in Java, use the explicit reference.

I stumbled over this thread searching for answer to similar case. Basically all answers are found, but it’s still hard to extract the essentials from them.

Kinds of Access

Assume a class Foo probably derived from some other class(es) with probably more classes derived from it.

  • from static method/getter of Foo
    • some probably overridden static method/getter:
      • this.method()
      • this.property
      • impossible by design
      • Foo.method()
      • Foo.property
      • impossible by design
      • some probably overridden static method/getter:
        • this.constructor.method()
        • this.constructor.property
        • this.method()
        • this.property
        • Foo.method()
        • Foo.property
        • not possible by intention unless using some workaround :
          • Foo.prototype.method.call( this )
          • Object.getOwnPropertyDescriptor( Foo.prototype,»property» ).get.call(this);

          Keep in mind that using this isn’t working this way when using arrow functions or invoking methods/getters explicitly bound to custom value.

          Background

          • When in context of an instance’s method or getter
            • this is referring to current instance.
            • super is basically referring to same instance, but somewhat addressing methods and getters written in context of some class current one is extending (by using the prototype of Foo’s prototype).
            • definition of instance’s class used on creating it is available per this.constructor .
            • this is available to refer to the definition of current class directly.
            • super is not referring to some instance either, but to static methods and getters written in context of some class current one is extending.

            Conclusion

            class A < constructor( input ) < this.loose = this.constructor.getResult( input ); this.tight = A.getResult( input ); console.log( this.scaledProperty, Object.getOwnPropertyDescriptor( A.prototype, "scaledProperty" ).get.call( this ) ); >get scaledProperty() < return parseInt( this.loose ) * 100; >static getResult( input ) < return input * this.scale; >static get scale() < return 2; >>class B extends A < constructor( input ) < super( input ); this.tight = B.getResult( input ) + " (of B)"; >get scaledProperty() < return parseInt( this.loose ) * 10000; >static get scale() < return 4; >>class C extends B < constructor( input ) < super( input ); >static get scale() < return 5; >>class D extends C < constructor( input ) < super( input ); >static getResult( input ) < return super.getResult( input ) + " (overridden)"; >static get scale() < return 10; >>let instanceA = new A( 4 ); console.log( "A.loose", instanceA.loose ); console.log( "A.tight", instanceA.tight );let instanceB = new B( 4 ); console.log( "B.loose", instanceB.loose ); console.log( "B.tight", instanceB.tight );let instanceC = new C( 4 ); console.log( "C.loose", instanceC.loose ); console.log( "C.tight", instanceC.tight );let instanceD = new D( 4 ); console.log( "D.loose", instanceD.loose ); console.log( "D.tight", instanceD.tight );

            If you are planning on doing any kind of inheritance, then I would recommend this.constructor . This simple example should illustrate why:

            class ConstructorSuper < constructor(n)< this.n = n; >static print(n) < console.log(this.name, n); >callPrint() < this.constructor.print(this.n); >> class ConstructorSub extends ConstructorSuper < constructor(n)< this.n = n; >> let test1 = new ConstructorSuper("Hello ConstructorSuper!"); console.log(test1.callPrint()); let test2 = new ConstructorSub("Hello ConstructorSub!"); console.log(test2.callPrint()); 
            • test1.callPrint() will log ConstructorSuper Hello ConstructorSuper! to the console
            • test2.callPrint() will log ConstructorSub Hello ConstructorSub! to the console

            The named class will not deal with inheritance nicely unless you explicitly redefine every function that makes a reference to the named Class. Here is an example:

            class NamedSuper < constructor(n)< this.n = n; >static print(n) < console.log(NamedSuper.name, n); >callPrint() < NamedSuper.print(this.n); >> class NamedSub extends NamedSuper < constructor(n)< this.n = n; >> let **** = new NamedSuper("Hello NamedSuper!"); console.log(****.callPrint()); let test4 = new NamedSub("Hello NamedSub!"); console.log(test4.callPrint()); 
            • ****.callPrint() will log NamedSuper Hello NamedSuper! to the console
            • test4.callPrint() will log NamedSuper Hello NamedSub! to the console

            See all the above running in babel repl .

            You can see from this that test4 still thinks it’s in the super class; in this example it might not seem like a huge deal, but if you are trying to reference member functions that have been overridden or new member variables, you’ll find yourself in trouble.

            Java static Keyword, Definition and Usage. The static keyword is a non-access modifier used for methods and attributes. Static methods/attributes can be accessed without creating an object of a class. Read more about modifiers in our Java Modifiers Tutorial. Java Keywords.

            Источник

            Saved searches

            Use saved searches to filter your results more quickly

            You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

            Get the methods of a JavaScript class.

            License

            IonicaBizau/class-methods

            This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

            Name already in use

            A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

            Sign In Required

            Please sign in to use Codespaces.

            Launching GitHub Desktop

            If nothing happens, download GitHub Desktop and try again.

            Launching GitHub Desktop

            If nothing happens, download GitHub Desktop and try again.

            Launching Xcode

            If nothing happens, download Xcode and try again.

            Launching Visual Studio Code

            Your codespace will open once ready.

            There was a problem preparing your codespace, please try again.

            Latest commit

            Git stats

            Files

            Failed to load latest commit information.

            README.md

            Buy Me A Coffee

            Get the methods of a JavaScript class.

            # Using npm npm install --save class-methods # Using yarn yarn add class-methods
            const classMethods = require("class-methods"); class Person  constructor (name)  this.setName(name); > setName (name)  this.name = name; > getName (name)  return this.name; > > class Worker extends Person  constructor (name, job)  super(name); this.setJob(job); > setJob (job)  this.job = job; > getJob (job)  return this.job; > static randomName ()  // Yes, it's random enough :D return ["Alice", "Bob"][0]; > > console.log(classMethods(Worker)); // [ 'setJob', 'getJob', 'setName', 'getName' ] console.log(classMethods(Person)); // [ 'setName', 'getName' ] console.log(classMethods(Worker,  deep: false >)); // [ 'setJob', 'getJob' ] console.log(classMethods(Worker,  includeStatic: true >)); // [ 'setJob', 'getJob', 'randomName', 'setName', 'getName' ]

            There are few ways to get help:

            1. Please post questions on Stack Overflow. You can open issues with questions, as long you add a link to your Stack Overflow question.
            2. For bug reports and feature requests, open issues. 🐛
            3. For direct and quick help, you can use Codementor. 🚀

            Get the methods of a JavaScript class.

            • Class input : The class you want to get the methods of.
            • Object options : An object containing the following fields:
            • deep (Boolean): If false the parent classes will not be iterated.
            • includeStatic (Boolean): If true , the static methods will be included too.

            Have an idea? Found a bug? See how to contribute.

            I open-source almost everything I can, and I try to reply to everyone needing help using these projects. Obviously, this takes time. You can integrate and use these projects in your applications for free! You can even change the source code and redistribute (even resell it).

            However, if you get some profit from this or just want to encourage me to continue creating stuff, there are few ways you can do it:

            • Starring and sharing the projects you like 🚀
            • —I love books! I will remember you after years if you buy me one. 😁 📖
            • —You can make one-time donations via PayPal. I’ll probably buy a coffee tea. 🍵
            • —Set up a recurring monthly donation and you will get interesting news about what I’m doing (things that I don’t share with everyone).
            • Bitcoin—You can send me bitcoins at this address (or scanning the code below): 1P9BRsmazNQcuyTxEqveUsnf5CERdq35V6

            💫 Where is this library used?

            If you are using this library in one of your projects, add it in this list. ✨

            Источник

            Читайте также:  Html form get inputs
Оцените статью