jjzjj

javascript - ES6 类/实例属性

coder 2025-03-24 原文

这将是一个相对较长的问题,但我真的很想了解。问题底部制定的最终问题。

我已经阅读了这个问题的答案:
ES6 class variable alternatives

关于为什么这在 ES6 中不被接受的语法的问题:

class MyClass {
    const MY_CONST = 'string';
    constructor(){
        this.MY_CONST;
    }
}

1)第一个答案提到:

Remember, a class definition defines prototype methods - defining variables on the prototype is generally not something you do.

我不明白;基于类的语言中的静态变量看起来与 JS 中原型(prototype)上定义的属性具有相同的目的。
显然不是像人名这样的实例变量,但它可以是车辆的默认 MAX_SPEED,或者是所有实例共享的计数器。如果实例没有覆盖原型(prototype)的 MAX_SPEED,它将返回到默认值。这不是静态变量的确切目的吗?

2) 以下post (ES6 规范提案)制定:

There is (intentionally) no direct declarative way to define either prototype data properties (other than methods) class properties, or instance property. Class properties and prototype data properties need be created outside the declaration.

我没有看到在类本身(在构造函数之外)中声明/初始化具有默认值的实例/类变量的实际区别?如果它在原型(prototype)上有什么关系?如果它涉及一个具有默认值的实例变量,该默认值可能适用于所有实例(但可覆盖),我看不出问题是什么。那么这个意图到底是什么?

3)ES6 class variable alternatives问题的第二个答案让我感到困惑(虽然不是来自技术 pov)。

From within a class method that variable can be accessed as this.constructor.foo (or MyClass.foo).

These class properties would not usually be accessible from to the class instance. i.e. MyClass.foo gives 'bar' but new MyClass().foo is undefined

这表明很明显可以在类(或底层函数)上声明一个类变量,如本例中所实现的:http://www.es6fiddle.net/iehn0hxp/

class Car{
  constructor(){
    //Set instance variable 
    this.instance_var = 220; 
    //Set class variable 
    this.constructor.class_var = 240; 
  }
}

var Mercedes = new Car(); 
var Audi = new Car(); 

//Instance property 
console.log(Mercedes.instance_var); //220 
//Class property 
console.log(Car.class_var); //240

//Set instance property 
Mercedes.instance_var = 120; //Well I don't know really :-) 
console.log(Mercedes.instance_var); //120 

//Class property 
Car.class_var = 140; 
console.log(Car.class_var); //140 
//Can be accessed from the constructor property on the instance
console.log(Mercedes.constructor.class_var); //140 
console.log(Audi.constructor.class_var); //140 

所以最终可以在类中声明一个静态属性;所以我看不出在构造函数中声明它与仅在类中定义它以及从外部定义它有什么区别?最后,将它作为实际的类定义放在构造函数中似乎只是一个微不足道的技术修改(结果将是相同的)。

仅使方法可用真的只是一种设计选择吗?
终极问题:

Because I don't understand how being a prototype-language changes the philosophy of having properties on the prototype against static variables on a class. It looks the same to me.

我希望我的问题很清楚,如果没有就大声说出来。

最佳答案

I don't get this; static variables in a class based language would appear to serve the same purpose as properties defined on the prototype in JS.

不,静态变量更像是在构造函数 上定义的属性。原型(prototype)上的变量将更接近实例变量,但它们几乎没有那么有用,因为它们在实例之间共享。 (因此,如果您修改原型(prototype)上的可变属性,它将反射(reflect)在该类型的所有其他实例中。)

我认为这也回答了您的其他问题,但回顾一下:

  • 原型(prototype)上的变量不像静态变量,因为它们似乎属于每个实例而不仅仅是类

  • 原型(prototype)上的变量不像实例变量,因为类的每个实例都没有自己的变量实例

  • 因此,原型(prototype)上的变量没有那么有用,它们应该分配给构造函数(实例变量)或分配构造函数(类变量)

  • 它们也是属性,不是变量

还有一个非 ES6 加糖的例子:

function Something() {
    this.instanceProperty = 5;
}

Something.staticProperty = 32;

Something.prototype.prototypeProperty = 977;

var s = new Something();
console.log(s.instanceProperty); // 5
console.log(s.prototypeProperty); // 977? If you want a class property,
                                  // this is not what you want
console.log(s.staticProperty); // undefined; it’s not on the instance
console.log(Something.staticProperty); // 32; rather, it’s on the class
console.log(Something.prototypeProperty); // undefined; this one isn’t

关于javascript - ES6 类/实例属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32545495/

有关javascript - ES6 类/实例属性的更多相关文章

  1. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  2. ruby-on-rails - 在混合/模块中覆盖模型的属性访问器 - 2

    我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah

  3. ruby-on-rails - 如何使用 instance_variable_set 正确设置实例变量? - 2

    我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击

  4. ruby 正则表达式 - 如何替换字符串中匹配项的第 n 个实例 - 2

    在我的应用程序中,我需要能够找到所有数字子字符串,然后扫描每个子字符串,找到第一个匹配范围(例如5到15之间)的子字符串,并将该实例替换为另一个字符串“X”。我的测试字符串s="1foo100bar10gee1"我的初始模式是1个或多个数字的任何字符串,例如,re=Regexp.new(/\d+/)matches=s.scan(re)给出["1","100","10","1"]如果我想用“X”替换第N个匹配项,并且只替换第N个匹配项,我该怎么做?例如,如果我想替换第三个匹配项“10”(匹配项[2]),我不能只说s[matches[2]]="X"因为它做了两次替换“1fooX0barXg

  5. ruby - 多个属性的 update_column 方法 - 2

    我有一个具有一些属性的模型:attr1、attr2和attr3。我需要在不执行回调和验证的情况下更新此属性。我找到了update_column方法,但我想同时更新三个属性。我需要这样的东西:update_columns({attr1:val1,attr2:val2,attr3:val3})代替update_column(attr1,val1)update_column(attr2,val2)update_column(attr3,val3) 最佳答案 您可以使用update_columns(attr1:val1,attr2:val2

  6. ruby - Nokogiri 剥离所有属性 - 2

    我有这个html标记:我想得到这个:我如何使用Nokogiri做到这一点? 最佳答案 require'nokogiri'doc=Nokogiri::HTML('')您可以通过xpath删除所有属性:doc.xpath('//@*').remove或者,如果您需要做一些更复杂的事情,有时使用以下方法遍历所有元素会更容易:doc.traversedo|node|node.keys.eachdo|attribute|node.deleteattributeendend 关于ruby-Nokog

  7. ruby-on-rails - Rails 模型——非持久类成员或属性? - 2

    对于Rails模型,是否可以/建议让一个类的成员不持久保存到数据库中?我想将用户最后选择的类型存储在session变量中。由于我无法从我的模型中设置session变量,我想将值存储在一个“虚拟”类成员中,该成员只是将值传递回Controller。你能有这样的类(class)成员吗? 最佳答案 将非持久属性添加到Rails模型就像任何其他Ruby类一样:classUser扩展解释:在Ruby中,所有实例变量都是私有(private)的,不需要在赋值前定义。attr_accessor创建一个setter和getter方法:classUs

  8. ruby-on-rails - Rails - 从另一个模型中创建一个模型的实例 - 2

    我有一个正在构建的应用程序,我需要一个模型来创建另一个模型的实例。我希望每辆车都有4个轮胎。汽车模型classCar轮胎模型classTire但是,在make_tires内部有一个错误,如果我为Tire尝试它,则没有用于创建或新建的activerecord方法。当我检查轮胎时,它没有这些方法。我该如何补救?错误是这样的:未定义的方法'create'forActiveRecord::AttributeMethods::Serialization::Tire::Module我测试了两个环境:测试和开发,它们都因相同的错误而失败。 最佳答案

  9. ruby-on-rails - RSpec:避免使用允许接收的任何实例 - 2

    我正在处理旧代码的一部分。beforedoallow_any_instance_of(SportRateManager).toreceive(:create).and_return(true)endRubocop错误如下:Avoidstubbingusing'allow_any_instance_of'我读到了RuboCop::RSpec:AnyInstance我试着像下面那样改变它。由此beforedoallow_any_instance_of(SportRateManager).toreceive(:create).and_return(true)end对此:let(:sport_

  10. ruby-on-rails - 使用 ruby​​ 将多个实例变量转换为散列的更好方法? - 2

    我收到格式为的回复#我需要将其转换为哈希值(针对活跃商家)。目前我正在遍历变量并执行此操作:response.instance_variables.eachdo|r|my_hash.merge!(r.to_s.delete("@").intern=>response.instance_eval(r.to_s.delete("@")))end这有效,它将生成{:first="charlie",:last=>"kelly"},但它似乎有点hacky和不稳定。有更好的方法吗?编辑:我刚刚意识到我可以使用instance_variable_get作为该等式的第二部分,但这仍然是主要问题。

随机推荐