Prototype, Constructor的使用和理解

[size=medium][b]JavaScript中Prototype的使用和实例[/b][/size]

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

</body>
</html>
<script>
(function(){
console.log("=========prototype的用法和误区=========");
var A = function(){};
A.prototype.A1 = function(){
console.log("A1");
};
A.prototype.A2 = [1,2,3];
A.prototype.A3 = 1;
var a1 = new A();
var a2 = new A();
a1.A2.push(4);
a1.A3 = 2;
console.log(a1.A3);//2
console.log(a2.A3);//1
console.log(a1.A2);//[1,2,3,4]
console.log(a2.A2);//[1,2,3,4]
/**
由于prototype是模版不是对象拷贝而是链接的方式
所以使用delete a1.A3, a1.A3并不会删除, 而是重新链上上一个值
**/
delete a1.A3;
console.log(a1.A3);//1
console.log(a2.A3);//1
delete a1.A2;
console.log(a1.A2);//[1,2,3,4]
console.log("=========以下是继承部分=========");
var B = function(){};
B.prototype = new A();
B.prototype.A3 = 10;
var b1 = new B();
console.log(b1.A3);//10
console.log("=========以下是constructor部分=========");
var C = function(){};
C.prototype = {
C1 : function(){}
};
var c = new C();
console.log(a1.constructor ===A);//true
/**
C.prototype = {
C1 : function(){}
};
等同于:
C.prototype = new Object({
C1 : function(){}
});
所以: c.constructor===C 为 false
**/
console.log(c.constructor===C);//false
console.log(c.constructor===Object);//true
console.log(C.prototype.constructor===Object);//true
})();
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值