简体   繁体   English

绑定一个类会失去它的静态属性

[英]Binding a class loses it's static properties

Given 给定

class someClass {
  constructor (str) {
    console.log('created', str);
  }
  static someStatic() {
  }
}

we can do 我们可以做的

const someBoundClass = someClass.bind(someClass, 'xxx');
const a = new someBoundClass(); // logs 'created xxx'
console.log(someClass.someStatic) // logs someStatic () {}
console.log(someBoundClass.someStatic) // logs undefined

What's happening behind the scenes causing me to be unable to access static properties on a bound class? 导致我无法访问绑定类上的静态属性的幕后发生了什么? Is there any way to achieve the desired bound effect without losing the static methods? 有什么方法可以在不损失静态方法的情况下实现所需的绑定效果吗?

Well bind creates a new function object, so I'm not sure why you would expect it to have the same static properties. 好的bind会创建一个新的函数对象,因此我不确定为什么您会期望它具有相同的静态属性。 Remember that ES6 class is mostly syntactic sugar: 请记住,ES6 class主要是语法糖:

function someClass(str) {
  if (!new.target) throw "constructor must be called with new";
  console.log('created', str);
}
someClass.someStatic = function() {};

var someBoundClass = someClass.bind(null, 'xxx');
console.log(someBoundClass === someClass) // false, of course

As a workaround, you might be able to use subclassing: 解决方法是,您可以使用子类化:

class someBoundClass extends someClass { constructor(...args) { super('xxx', ...args); }}
const a = new someBoundClass(); // logs 'created xxx'
console.log(someClass.someStatic) // logs someStatic () {}
console.log(someBoundClass.someStatic) // logs someStatic () {}

The someBoundClass here inherits the static properties from someClass . someBoundClass这里继承静态属性someClass

Take a look into Javascript static vs instance, prototype keyword 看看Javascript静态与实例,原型关键字

There is a difference between setting a property to an object, what is done when using static and adding a method to each instance of the object, which can be done by using someClass.prototype.someMethod or in your case by just removing static . 在为对象设置属性,使用static与将方法添加到对象的每个实例之间有区别,这可以通过使用someClass.prototype.someMethod或在您的情况下通过删除static

That means undefined would also occur, if you try to call someStatic on a instance of someClass , which was instantiated directly by new someClass("xxx") . 这意味着undefined也会发生,如果您尝试调用someStatic上的实例someClass ,这是直接被实例化new someClass("xxx")

For another approach take a look at the answer of Bergi. 对于另一种方法,请看一下Bergi的答案。

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

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