<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js oop 总结</title> </head> <body> <script> /*1 原始方式 *缺点:需要创建多个car实例,推荐等级★ */ var ocar = new Object(); ocar.color = "blue"; ocar.doors = 4; ocar.mpg = 25; ocar.showColor = function(){ alert(this.color); } ocar.showColor(); //2 原始工厂方式 //缺点:重复生成函数,推荐等级★★ function createCar(){ var oTempCar = new Object(); oTempCar.color = "blue"; oTempCar.doors = 4; oTempCar.mpg = 25; oTempCar.showColor = function(){ alert(this.color); } return oTempCar; } var oCar1 = createCar(); var oCar2 = createCar(); oCar1.showColor(); oCar2.showColor(); //3 在工厂函数外定义对象的方法,推荐等级★★★ function showColor() { alert(this.color); } function createCar(sColor,iDoors,iMpg) { var oTempCar = new Object; oTempCar.color = sColor; oTempCar.doors = iDoors; oTempCar.mpg = iMpg; oTempCar.showColor = showColor; return oTempCar; } var oCar1 = createCar("red",4,23); var oCar2 = createCar("blue",3,25); oCar1.showColor(); //输出 "red" oCar2.showColor(); //输出 "blue" //4 构造函数方式 //缺点:构造函数会重复生成函数,推荐等级★★ function Car(sColor,iDoors,iMpg){ this.color = sColor; this.doors = iDoors; this.mpg = iMpg; this.showColor = function(){ alert(this.color); } } var oCar1 = new Car("red",4,23); var oCar2 = new Car("blue",3,25); oCar1.showColor(); oCar2.showColor(); //5 原型方式, //缺点:必须在对象创建后才能改变属性的默认值,推荐等级★★ function Car(){} Car.prototype.color = "blue"; Car.prototype.doors = 4; Car.prototype.mpg = 25; Car.prototype.showColor = function(){ alert(this.color); } var oCar1 = new Car(); var oCar2 = new Car(); oCar1.showColor(); oCar2.showColor(); //我和我的小伙伴惊呆了 //缺点2:真正的问题出现在属性指向的是对象,而不是函数时。函数共享不会造成问题,但对象却很少被多个实例共享 function Car(){} Car.prototype.color = "blue"; Car.prototype.doors = 4; Car.prototype.mpg = 25; Car.prototype.drivers = new Array("Mike","John"); Car.prototype.showColor = function(){ alert(this.colorj); } var oCar1 = new Car(); var oCar2 = new Car(); oCar1.drivers.push("Bill"); alert(oCar1.drivers); alert(oCar2.drivers); //6混合的构造函数/原型方式 //即用构造函数定义对象的所有非函数属性,用原型方式定义对象的函数属性(方法) //推荐等级★★★★★ 八心八箭,吐血推荐 //目前使用最广泛的是混合的构造函数/原型方式 function Car(sColor,iDoors,iMpg){ this.Color = sColor; this.doors = iDoors; this.mpg = iMpg; this.drivers = new Array("Mike","John"); } Car.prototype.showColor = function(){ alert(this.color); } var oCar1 = new Car("red",4,23); var oCar2 = new Car("blue",45,41); oCar1.drivers.push("Bill"); alert(oCar1.drivers); alert(oCar2.drivers); </script> </body> </html>
参考资料: http://www.w3school.com.cn/js/pro_js_object_defining.asp
时间: 2024-10-12 13:32:16