简体   繁体   English

您如何在自定义类上调用静态方法? JS

[英]How do you call a static method on a custom class? JS

In javascript, I've created a class Group that creates an empty array named items and returns it. 在javascript中,我创建了一个类Group,该类创建了一个名为items的空数组并将其返回。

But I'm trying to create a static method from(){} that takes an iterable object and creates a new Group from that iterable obj. 但是我正在尝试从(){}创建一个静态方法,该方法采用一个可迭代的对象,并从该可迭代的obj创建一个新的Group。

I'm trying this.items.push() but its not working how I'd expect it to 我正在尝试this.items.push(),但无法正常工作

class Group(){
 constructor(){
   this.items = []
 }
 from(obj){
  for(let item of obj){this.items.push(item)}
 }
}

i'd implement it like so: 我会这样实现:

let group = Group.from([10, 11))//random numbers     

it unfortunately returns the following error: 不幸的是,它返回以下错误:

TypeError: Cannot read property 'push' of undefined (line 37 in function 
Function.from)

You have a syntax error: 您有语法错误:

class Group(){

should be: 应该:

class Group { // no parameter list here

as in the class syntax, the parameters are defined in the constructor function. 与类语法中一样,参数在构造函数中定义。

Where a constructor adds methods to "class" instances as below, the method is available to instances, not the constructor itself. 如下所示,在构造函数将方法添加到“类”实例的情况下,该方法可用于实例,而不是构造函数本身。 You you have to create an instance, then call the method: 您必须创建一个实例,然后调用该方法:

 class Group { constructor () { this.items = []; } from (obj) { for (let item of obj) { this.items.push(item); } } } var group = new Group(); group.from([1,2]); console.log(group.items); // 1, 2 console.log(typeof Group.from); // undefined 

Although there are drafts for new static syntax on JS classes, you'll currently need to use the prototype for static methods / properties. 尽管针对JS类提供了新的静态语法的草案,但您目前仍需要将原型用于静态方法/属性。

class Group {
  constructor(){
    this.items = []
  }
}

Group.prototype.from = function(obj){
  var group = new Group;
  for(let item of obj) group.items.push(item);
  return group;
}

let group = aGroudInstance.from([10, 11]);

You probably want to simply add the method onto the Group class (object) like so: 您可能希望将方法简单地添加到Group类(对象)上,如下所示:

Group.from = function(...) ...;

As it's not actually making use of being a static method, and would unnecesarily require an instance of a Group -- unless you used it like so: Group.prototype.from(...) . 因为它实际上并没有利用静态方法,并且会不必要地需要Group的实例-除非您这样使用: Group.prototype.from(...)

It's a factory function. 这是工厂功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM