【问题标题】:How to write a JavaScript template class?如何编写一个 JavaScript 模板类?
【发布时间】:2011-08-08 03:27:33
【问题描述】:

我只是 JavaScript 的新手。我想写一个像 C++ 这样的 JS 模板类。例如:

template <typename T>
class A
{
public:
    A(T x)
    {
        this.a=x;
    }
    ~A()
    {

    }
    void print()
    {
        std::cout<<a<<std::endl;
    }
private:
    T a;
};

我们可以这样使用这个类:

A<int> test(2);
test.print();

对于 C++,这很简单。但是在JS中,怎么解释呢?非常感谢。

【问题讨论】:

  • 为什么需要动态类型语言的模板类?
  • 我只是把C++代码翻译成JS代码,然后来这个问题。这个翻译有什么办法吗?

标签: javascript class templates


【解决方案1】:

Javascript 不需要模板来处理泛型类型,因为 Javascript 是 dynamically typed language。这意味着在 Javascript 中,函数可以接受任何类型的参数。

要实现与您问题中的示例模板相同的功能,您可以使用此(更短的)Javascript 代码和对象文字:

var A = {
  print: function(value) {
    document.write(value);
  }
}

可以这样使用:

A.print(2);

您可以在 JsFiddle 上查看此代码示例。

如果您希望代码更接近 C++,您可以使用此方法,使用函数代替:

var A = function(value) {
  return {
    print: function() {
      document.write(value);
    }
  }
}

可以这样使用:

var test = A(2);
test.print();

您可以在JsFiddle 上看到这一点。

【讨论】:

  • 我明白了。谢谢你和 mVChr :)
【解决方案2】:

你可以这样做:

var A = function ( x ) {
    var a = x;
    this.print = function () {
        console.log(a);
    };
};

var test = new A(2);
test.print(); // -> 2

在这种情况下,变量a 是私有的,函数print 是公共的(与this 的任何其他属性一样),A 是模板(原型对象)的构造函数。

【讨论】:

  • 也许可行,但使用这种方法无法反映“模板”。如果没有其他方法,也许这是一个好方法。谢谢..
【解决方案3】:

在你的情况下,由于模板参数是一种类型,你不需要在 Javascript 中反映它。

但如果你有类似函数指针的东西

typedef bool (*C) (const int&, const int&);

template<C c>
class my_class{

public:
    void my_method(){
        // use c 
        // ...
    }

};

你可以翻译成

var my_class_t = function(c){

    var my_class = function(){
    };

    my_class.prototype.my_method = function(){
        // use c 
        // ...
    };

    return my_class;
};

并按如下方式使用

var my_class = my_class_t(function(a, b){return a < b;});
var my_instance = new my_class();
my_instance.my_method();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    • 2011-04-14
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多