代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Prototype Study</title>
<script type="text/javascript" charset="utf-8">
function Person(id) {
this.id = id;
}
Person.prototype = {
// constructor : Person,
name : 'z3',
age : 25,
job : 'programmer',
say : function () {
window.document.write('我是原型对象中的方法.' + '<br><br>');
}
}
// ECMA5 给原型对象重新设置构造器的方法 Object.defineProperty()
/*
3 个参数
第一个参数: 重设构造器的对象
第二个参数: 设置什么属性
第三个参数: options配置项
*/
Object.defineProperty(Person.prototype, 'constructor',{
emumerable : false,
value : Person
});
var p = new Person('N0001');
p.say();
document.write(p.id + '<br><br>');
//输出原型对象的构造器
document.write(Person.prototype.constructor + '<br><br>');
//枚举对象的属性和方法
//使用for in 不会输出constructor属性 因为已经设置emumerable 为false
for (var attr in p){
document.write(attr + '<br>');
}
/**
* 原型对象的动态特性
*/
function ProgramLanguage() {
}
var c = new ProgramLanguage();
ProgramLanguage.prototype = {
name : 'javascript',
helloWorld : function () {
document.write('<br><br><br>' + 'Hello world, welcome to javascript.' + '<br><br><br>');
}
}
// c.helloWorld(); //error : Uncaught TypeError: c.helloWorld is not a function
var c2 = new ProgramLanguage();
c2.helloWorld(); // it's OK
</script>
</head>
<body>
</body>
</html>
结果: