【发布时间】:2018-10-01 11:22:45
【问题描述】:
我正在尝试学习对象和 JavaScript。
我遇到的问题是,似乎以下两个都做同样的事情。我的研究没有表明存在什么(如果有的话)差异,但这可能是因为很难在搜索框中质疑这一点。
在代码中,我添加了 cmets 以强调差异
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id = "results"></div>
<script>
"use strict";
const results = document.getElementById("results");
const Thing = function(){ /* ****** THIS */
var _x;
this.set = function(x){
_x = x;
},
this.alert = function(){
results.innerHTML += _x + "<br />";
};
};
function Other(){ /* ****** AND THIS */
var _x;
this.set = function(x){
_x = x;
},
this.alert = function(){
results.innerHTML += _x + "<br />";
};
};
const t = new Thing();
t.set("b");
t.alert();
const t2 = new Thing();
t2.set("b2");
t2.alert();
t.alert();
t2.alert();
const o = new Other();
o.set("d");
o.alert();
const o2 = new Thing();
o2.set("d2");
o2.alert();
o.alert();
o2.alert();
</script>
</body>
</html>
有什么区别还是两者都有效?
编辑
我看到了重复的var functionName = function() {} vs function functionName() {}。问题之间的区别在于我使用了new 这个词。我的问题是,这真的有影响吗?
【问题讨论】:
-
@CRice 是不是也一样,因为我看到的区别是我的例子,使用了
new这个词。当然,我很高兴接受这个骗局(并且为了记录,我首先进行了 Google 搜索),但如果能确定这一点,那就太好了,也让人放心
标签: javascript