简体   繁体   English

Object.create是否支持所谓的类方法?

[英]Does Object.create support so called class methods?

When I create an object using a constructor like: 当我使用类似构造函数的对象时:

function Person(name, age) {
  this.name = name;
  this.age = age;
 }

I can add properties that are functions to the constructor function which act like (static) class methods. 我可以将作为函数的属性添加到构造函数中,这些函数的作用类似于(静态)类方法。 Object.create doesn't seem to support that. Object.create似乎不支持该功能。 Is that right? 那正确吗? The constructor property of all object created by Object.create seem to be the same function. Object.create创建的所有对象的构造函数属性似乎都是相同的函数。

Thanks in advance. 提前致谢。

Are you sure you mean static ? 您确定是static吗?

What I mean is, in a more class-dependent language, you might have: 我的意思是,用一种更加依赖类的语言,您可能会:

class Person {

    static people = 0;

    public name;
    public age;

    public Person (name, age) { this.name = name; this.age = age; Person::people += 1; }
    public sayName () { echo this.name; }

    static numPeople () { echo Person::people; }
}

Then you might say: 然后您可能会说:

bob = new Person("Bob", 32);
bob.sayName(); // "Bob"
Person::numPeople(); // 1

If you wanted Person::numPeople(); 如果您想要Person::numPeople(); functionality, there's nothing stopping you from adding Object.create.numPeople = function () {}; 功能,没有什么可以阻止您添加Object.create.numPeople = function () {};

The question you might want to ask yourself is "Why?" 您可能要问自己的问题是“为什么?”

Are you trying to call static methods like: 您是否正在尝试调用静态方法,例如:

bob.constructor.numPeople();

If so, I'm sure that there's a better way around that. 如果是这样,我相信有更好的解决方法。 For example, extending the constructor's prototype would provide access to static properties/methods by default. 例如,扩展构造函数的原型将默认提供对静态属性/方法的访问。

var personObj = {
    sayName : function () { console.log(this.name); },
    sayAge : function () { console.log(this.age); }
};

var bob = Object.create(personObj, { name : "Bob", age : 32 });

These are accessed in a way which is similar to traditional inheritance, but static in the sense that each object references the same functions and values, so if that prototype object changes, each constructed instance changes, as well. 它们的访问方式类似于传统继承,但在每个对象都引用相同的函数和值的意义上是静态的,因此,如果原型对象发生更改,则每个构造的实例也将发生更改。

Personally, I prefer the freedom of doing most of my object creation inline and on-demand. 就个人而言,我更喜欢自由地内联和按需执行大多数对象创建。 If I need to create multiples of the same format, then I'll typically create a factory, rather than creating a constructor or using Object.create. 如果需要创建相同格式的倍数,则通常将创建工厂,而不是创建构造函数或使用Object.create。

With a factory, even just a simple one, using one or two levels of closure, you can simulate private properties/methods, and with the second closure, you can simulate "class-wide" private-statics. 对于一个工厂,甚至只是一个简单的工厂,使用一个或两个级别的闭包,您可以模拟私有属性/方法,而对于第二个闭包,则可以模拟“类范围”的私有静态。

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

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