I'm a C++ programmer who recently landed on the JavaScript world; now I'm trying to apply some of the dessign patterns of C++ to JavaScript for the sake of my understanding and mental health.
AFAIK, the following codes are kind of equivalent in C++ and Javascript:
C++
// Class definition
template <typename T> class foo
{
public:
// Constructor
foo(T value) { this->value = value; }
// Public function
T twice() { return this->value + this->value; }
private:
// Private function
void bar() { }
// Private member
T value;
};
JavaScript
// "Class" definition and constructor
function foo(value)
{
// "Private" member
this.value = value;
// "Private" function
this.bar = function() { };
}
// Public function
foo.prototype.twice = function() { return this.value + this.value; };
The usage of both classes are similar too:
C++ live demo
foo<int> f1(1);
foo<std::string> f2("1");
std::cout << f1.twice() << '\n'; // output: 2
std::cout << f2.twice() << '\n'; // output: 11
JavaScript live demo
var f1 = new foo(1);
var f2 = new foo('1');
print(f1.twice()); // output: 2
print(f2.twice()); // output: 11
But there's a thing that cannot be done with a JavaScript class and is possible to do with a C++ class: the use of a temporary RValue to do a task:
C++
std::cout << foo<float>(3.14f).twice() << '\n'; // output: 6.28
JavaScript
print(foo(3.14).twice()); // Uncaught TypeError: undefined is not a function
I think that the error on the JavaScript version is due to the fact that foo is a function and it returns nothing (undefined
), so at first I was thinking of change the constructor with the code below:
JavaScript
// "Class" definition and constructor
function foo(value)
{
// "Private" member
this.value = value;
// "Private" function
this.bar = function() { };
return this; // <----- new code!
}
But this doesn't work at all; the object returned by the return this;
instruction isnt of type foo
(foo(3.14) instanceof foo
is false
).
While debugging in Chrome 35.0.1916.114 the type of this
in the instruction return this;
is foo
but the type changes to window
in this situation:
var x = foo(3.14); // x is typeof window
Once made the introduction, here comes the questions:
- Why the type of
this
isfoo
inside the constructor andwindow
when captured outside?- Is because the
new
operator isn't used?
- Is because the
- Is there a way to create JavaScript objects that behave like C++ RValues?