【发布时间】:2014-07-24 23:38:26
【问题描述】:
我是一名最近进入 JavaScript 世界的 C++ 程序员;现在,为了我的理解和心理健康,我正在尝试将 C++ 的一些设计模式应用于 JavaScript。
AFAIK,以下代码在 C++ 和 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; };
这两个类的用法也很相似:
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
但是有一件事情是 JavaScript 类无法做到的,而 C++ 类却可以做到:使用临时 RValue 来完成任务:
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
我认为 JavaScript 版本的错误是由于 foo 是一个函数并且它什么都不返回(undefined),所以起初我想用下面的代码更改构造函数:
JavaScript
// "Class" definition and constructor
function foo(value)
{
// "Private" member
this.value = value;
// "Private" function
this.bar = function() { };
return this; // <----- new code!
}
但这根本行不通; return this; 指令返回的对象不是foo 类型(foo(3.14) instanceof foo 是false)。
在 Chrome 35.0.1916.114 中调试时,指令 return this; 中 this 的类型为 foo,但在这种情况下类型更改为 window:
var x = foo(3.14); // x is typeof window
介绍完毕,问题来了:
- 为什么
this的类型在构造函数内部是foo,而在外部捕获时是window?- 是因为没有使用
new运算符吗?
- 是因为没有使用
- 有没有办法创建行为类似于 C++ RValues 的 JavaScript 对象?
【问题讨论】:
-
我读过的最好的问题之一 :)。 +1 现场演示等。
标签: javascript c++ class oop