使用prototype关键字和点标记法为构造器添加属性和方法
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<body>
<script>
function test(){};
test.prototype.var1="var1";
test.prototype.func1=function(){
alert("func1");
};
var test1 = new test();
alert(test1.var1);
test1.func1();
</script>
</body>
</html>
通过对象直接量为构造函数添加属性和方法
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<body>
<script>
function test(){};
test.prototype = {
var1:"var1",
func1:function(){
alert("func1");
}
};
var test1 = new test();
alert(test1.var1);
test1.func1();
</script>
</body>
</html>
prototype有一个强大的特性,允许在对象实例已经被创建之后继续添加属性和方法,而新添加的属性和方法会自动添加到所有对象实例中,不管是已创建的还是将要创建的。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<body>
<script>
function test(){};
test.prototype = {
var1:"var1",
func1:function(){
alert("func1");
}
};
var test1 = new test();
alert(test1.var1);
test1.func1();
test.prototype.func2=function(){
alert("func2");
};
test1.func2();
</script>
</body>
</html>