首页 > 编程语言 > 详细

Javascript 面向对象编程(一):封装

时间:2017-06-27 14:22:30      阅读:212      评论:0      收藏:0      [点我收藏+]

构造函数

1.构造函数方法很好用,但是存在一个浪费内存的问题

function Cat(name, color) {
    this.name = name;
    this.color = color;
    this.type = "猫科动物";
    this.eat = function () { alert("吃老鼠"); };
}

var cat1 = new Cat("大毛", "黄色");
var cat2 = new Cat("二毛", "黑色");
alert(cat1.type); // 猫科动物
cat1.eat(); // 吃老鼠

2.Prototype模式,所有实例的type属性和eat()方法,其实都是同一个内存地址,指向prototype对象,因此就提高了运行效率。

function Cat(name, color) {
    this.name = name;
    this.color = color;
}
Cat.prototype.type = "猫科动物";
Cat.prototype.eat = function () { alert("吃老鼠") };
var cat1 = new Cat("大毛", "黄色");
var cat2 = new Cat("二毛", "黑色");
alert(cat1.type); // 猫科动物
cat1.eat(); // 吃老鼠
alert(cat1.eat == cat2.eat); //true

 

Javascript 面向对象编程(一):封装

原文:http://www.cnblogs.com/cnki/p/7084839.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!