<!--论对js原型的理解-->
<!DOCTYPE html>
<
html lang=
"en">
<
head>
<
meta charset=
"UTF-8">
<
title>Title</
title>
</
head>
<
body>
<!--js中的原型同比其他面向对象语言中的class(类)-->
<
script>
/*构造函数模式,弊端浪费内存*/
//1.先写一个原型函数
function Cat(name,color){
this.
name=name;
this.
color=color;
this.
type=
"猫科动物";
this.
eat=
function(){
alert(
"吃老鼠可以,跟我抢鱼吃就是它的不对了!");
}
}
// 2.创建实例对象,继承原型函数
var cat1 =
new Cat(
'大毛',
'黄色');
var cat2 =
new Cat(
'二毛',
'白色');
alert(
cat1.
name+
":"+
cat1.
color+
":"+
cat1.
type);
cat1.
eat();
/*prototype模式,解决构造函数浪费内存的问题。由于在js中,
每一个构造函数都有一个prototype属性,指向另一个对象,
这个对象的属性和方法,都会被构造函数的实例继承。所以,可以
将构造函数中原型函数固定不变的属性和方法直接定义在prototype上.*/
function Cat(name,color){
this.
name=name;
this.
color=color;
}
Cat.
prototype.
type=
"猫科动物";
Cat.
prototype.
eat=
function(){
alert(
"吃老鼠可以,跟我抢鱼吃就是它的不对了!")
}
var cat1=
new Cat(
"大毛",
"黄色");
alert(
cat1.
name+
":"+
cat1.
color+
":"+
cat1.
type);
cat1.
eat();
</
script>
</
body>
</html>
//详情可参考文章阮一峰的网络日志 javascript面向对象编程
http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_encapsulation.html
转载请注明原文地址: https://ju.6miu.com/read-969278.html