您的位置:首页 > 其它

不同的函数定义方式,new出不同的结果

2016-07-13 19:47 211 查看
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>

</body>
<!--不同的函数定义方式,new出不同的结果-->
<script>

function person() {
this.name = 'd1';
this.getName = function () {
return name;
};
this.setName = function (newName) {
name = newName;
};

}

console.log(new person().getName());
console.log(new person());
var p = new person();
console.log(p instanceof person); //true
//console.log(setName('bb'));

</script>
<script>
function Person() {
this.name = 'd2';
return {
getName: function () {
return name;
},
setName: function (newName) {
name = newName;
}
}
}

console.log(new Person().getName());
console.log(new Person());
var p = new Person();
console.log(p instanceof Person);  //false
p.setName("Tom");
console.log(p.getName());
</script>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: