【问题标题】:Does the Dart programming language have an equivalent to Javascript's "prototype"?Dart 编程语言是否有相当于 Javascript 的“原型”?
【发布时间】:2012-09-21 22:21:53
【问题描述】:

在 Dart 中,函数是否可以有与之关联的原型?

示例 Javascript 代码:

doStuff.prototype.isDefined = true; //is there anything like Javascript's function prototypes in Dart?
function doStuff(){
    console.log("The function doStuff was called!");
}

是否可以在 Dart 中做与此等效的操作(即,为每个函数创建一个属性列表?)

【问题讨论】:

    标签: dart


    【解决方案1】:

    这里要解决两件事:

    首先,Dart 没有原型或原型继承,而是使用经典继承。对象不是原型,而是类,对象不是原型链,而是超类。

    其次,对于您的具体情况,我认为我们必须了解更多您需要做的事情才能找出在 Dart 中执行此操作的惯用方式。应该很快就可以使用对象来模拟函数,这样您就可以调用一个对象并且仍然拥有与之关联的状态和其他方法。

    查看这篇文章了解更多:http://www.dartlang.org/articles/emulating-functions/

    当该功能落地时,您将能够做到这一点:

    class DoStuff {
      bool isDefined = true;
      call() => print("The function doStuff was called!");
    }
    var doStuff = new DoStuff();
    
    main() => doStuff();
    

    如果您有一组固定的关于您需要跟踪的函数的元数据,则此方法有效。它与 JavaScript 略有不同,因为函数的每个实例是 Dart 将有它自己的状态 isDefined。我不确定是否有可能或容易获得函数的多个实例是 JavaScript,但您可能需要将 isDefined 设为静态,以便在所有实例之间共享该值。

    【讨论】:

      【解决方案2】:

      Dart 不允许您在运行时从类的实例中添加或删除成员变量。用 Dart 重写你的例子,它可能看起来像这样:

      class doStuff {
        bool isDefined;
        doStuff() {
          isDefined = true;
        }
        void stuff() {
          print('The function stuff was called!');
        }
      }
      
      main() {
        new doStuff().stuff();
      }
      

      如果你想在 Dart 中为一个类添加一个属性包,你可以这样写:

      class PropertyObject {
        Map<String, Dynamic> properties;
      
        PropertyObject() {
          properties = new Map<String, Dynamic>();
        }
      
        Dynamic operator[](String K) => properties[K];
        void operator[]=(String K, Dynamic V) => properties[K] = V;
      }
      
      main() {
        PropertyObject bag = new PropertyObject();
        bag['foo'] = 'world';
        print('Hello ${bag['foo']}');
      }
      

      请注意,您不能使用“.”访问地图属性。运算符。

      【讨论】:

      • 我惊讶地发现从 Javascript 到 Dart 的转换比原来的 Javascript 版本更冗长。
      • 另一种方法是实现 Function 接口:
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-20
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 2019-10-23
      相关资源
      最近更新 更多