I'm just a newer to JavaScript. I want to write a JS template class like C++. for example:
template <typename T>
class A
{
public:
A(T x)
{
this.a=x;
}
~A()
{
}
void print()
{
std::cout<<a<<std::endl;
}
private:
T a;
};
We can use this class like this:
A<int> test(2);
test.print();
For C++, it's simple. But in JS, how it can be explained? Thanks very much.
1. What is the syntax of class template? Explanation: Syntax involves template keyword followed by list of parameters in angular brackets and then class declaration.
Class methods are created with the same syntax as object methods. Use the keyword class to create a class. Always add a constructor() method. Then add any number of methods.
For example: template<class L, class T> class Key; This reserves the name as a class template name. All template declarations for a class template must have the same types and number of template arguments.
We can define a template for a class. For example, a class template can be created for the array class that can accept the array of various types such as int array, float array or double array.
Javascript does not need templates to handle generic types because Javascript is a dynamically typed language. This means that in Javascript, functions can accept arguments of any type.
To achieve the same functionality as the example template in your question, you may use this (much shorter) Javascript code using object literals:
var A = {
print: function(value) {
document.write(value);
}
}
This can be used like so:
A.print(2);
You can see this code sampe in action on JsFiddle.
If you want the code to correspond more closely to the C++, you can use this approach using a function instead:
var A = function(value) {
return {
print: function() {
document.write(value);
}
}
}
Which can be used like this:
var test = A(2);
test.print();
You can see this in action on JsFiddle.
You could do this:
var A = function ( x ) {
var a = x;
this.print = function () {
console.log(a);
};
};
var test = new A(2);
test.print(); // -> 2
In this case, the variable a
is private, the function print
is public (as is any other property of this
), and A
is the constructor function for the template (prototype object).
Well in your case, since the template parameter is a type, you don't need to reflect it in Javascript.
But if you had something like a function pointer
typedef bool (*C) (const int&, const int&);
template<C c>
class my_class{
public:
void my_method(){
// use c
// ...
}
};
You could translate it to
var my_class_t = function(c){
var my_class = function(){
};
my_class.prototype.my_method = function(){
// use c
// ...
};
return my_class;
};
And use it as follows
var my_class = my_class_t(function(a, b){return a < b;});
var my_instance = new my_class();
my_instance.my_method();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With