js 原型模型重写1

时间:2023-11-29 11:57:26
 <!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title> <script type="text/javascript"> function Person(){ } /**
* 使用如下犯法来编写代码,当属性和方法特别多的时候,编写起来不是很方便,
* 可以通过json的格式 Person.prototype.name = "Leon";
Person.prototype.age = 23;
Person.prototype.say = function(){
console.info(this.name + " " + this.age);
}
*/
/**
* 以下方式将会重写原型
* 由于原型重写,而且没有通过Person.propotype来指定,
* 此时的constructor不会指向Person而是指向Object,
* 如果constructor真的比较重要,可以在json中说明原型的指向constructor : Person ,
*/
Person.prototype = {
// constructor : Person ,//手动指定constructor
name : "Leon",
age : 23,
say : function(){
console.info(this.name + " , " + this.age);
}
} var p1 = new Person();
p1.say(); //Leon , 23
console.info(p1.constructor == Person); //false 如果取消注释掉的constructor : Person , 此时结果为true
console.info(p1.constructor); // Object() 如果取消注释掉的constructor : Person , 此时结果为Person() </script> </head>
<body> </body>
</html>
 <!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title> <script type="text/javascript"> function Person(){ } var p1 = new Person(); Person.prototype.sayHi = function(){
console.info(this.name + " : hi ");
for(var o in Person.prototype){
console.info(o);
}
}
p1.sayHi(); //undefined : hi sayHi /**
* 如果把重写放置在new Person()之后,注意内存模型
*/
Person.prototype = {
// constructor : Person ,//手动指定constructor
name : "Leon",
age : 23,
say : function(){
console.info(this.name + " , " + this.age);
}
}
p1.sayHi();////undefined : hi name age say var p2 = new Person();
p1.say(); //TypeError: p1.say is not a function
p2.say(); //Leon , 23
p2.sayHi(); //TypeError: p2.sayHi is not a function </script> </head>
<body> </body>
</html>

js 原型模型重写1

但又存在另外一种问题:

 <!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title> <script type="text/javascript"> /**
* 基于原型的创建虽然可以有效的完成封装,但是依然有一些问题
* 1 无法通过构造函数来设置属性值
* 2 当属性中的引用类型变量是可能存在变量值重复
*/
function Person(){ }
Person.prototype = {
constructor : Person,
name : "Leon" ,
age : 30 ,
friends : ["Ada","Chris"],
say : function(){
console.info(this.name + "[" + this.friends + "]");
}
} var p1 = new Person();
p1.name = "Jhon";
p1.say(); //Jhon[Ada,Chris] console.info(p1.__proto__);
/**
* 输出结果:
* age 30
* friends ["Ada", "Chris", "Mike"]
* name "Leon"
* constructor Person()
* say function()
*/ var p2 = new Person();
p2.say(); //Leon[Ada,Chris] //会在原型中找friends,所有Mike是在原型中增加的
p1.friends.push("Mike"); //为p1增加了一个朋友
//此时原型汇总就多了一个mike,这就是原型带来的第二个问题
p1.say(); //Jhon[Ada,Chris,Mike]
p2.say(); //Leon[Ada,Chris,Mike]
console.info(p1.__proto__);
console.info(p2.__proto__);
/**
* 输出结果:
* age 30
* friends ["Ada", "Chris", "Mike"]
* name "Leon"
* constructor Person()
* say function()
*/ </script> </head>
<body> </body>
</html>