我是一名C++程序员,最近刚接触到JavaScript世界;为了理解和心理健康,我现在正在尝试将C++的一些设计模式应用到JavaScript中。
下面的代码在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
)。
在Chrome35.0.1916.114中调试时,指令return this;
中的this
类型为foo
,但在这种情况下,类型更改为window
:
var x = foo(3.14); // x is typeof window
一旦做了介绍,问题就来了:
this
类型为foo
,window
类型为window
?new
运算符不是type
https://stackoverflow.com/questions/24035431
复制相似问题