Javascript中界说类(class)的几种要领总结
发布时间:2018-08-13 07:43:48 所属栏目:创业 来源:站长网
导读:要领一:工场方法--- 建设并返回特定范例的工具的 工场函数 ( factory function ) function createCar(color,doors,mpg){ var tempCar = new Object; tempCar.color = color; tempCar.doors = doors; tempCar.mpg = mpg; tempCar.showCar = function(){ al
要领一:工场方法--- 建设并返回特定范例的工具的 工场函数 ( factory function ) function createCar(color,doors,mpg){ var tempCar = new Object; tempCar.color = color; tempCar.doors = doors; tempCar.mpg = mpg; tempCar.showCar = function(){ alert(this.color + " " + this.doors); } return tempCar; } 要领二:结构函数方法--- 结构函数看起来很像工场函数 function Car(color,doors,mpg){ this.color = color; this.doors = doors; this.mpg = mpg; this.showCar = function(){ alert(this.color); }; } 要领三:原型方法--- 操作了工具的 prototype 属性,可把它当作建设新工具所依靠的原型 function Car(color,doors,mpg){ this.color = color; this.doors = doors; this.mpg = mpg; this.drivers = new Array("nomad","angel"); } Car.prototype.showCar3 = function(){ alert(this.color); }; 要领四:殽杂的结构函数 /原型方法--- 用结构函数界说工具的全部非函数属性,用原型方法界说工具的函数属性(要领) function Car(sColor, iDoors, iMpg) { this.color = sColor; this.doors = iDoors; this.mpg = iMpg; this.drivers = new Array("Mike", "Sue"); } Car.prototype.showColor = function () { alert(this.color); }; 要领五:动态原型要领--- 在结构函数内界说非函数属性,而函数属性则操作原型属性界说。独一的区别是赋予工具要领的位置。 function Car(sColor, iDoors, iMpg) { this.color = sColor; this.doors = iDoors; this.mpg = iMpg; this.drivers = new Array("Mike", "Sue"); if (typeof Car._initialized == "undefined") { Car.prototype.showColor = function () { alert(this.color); }; Car._initialized = true; } } //该要领行使符号( _initialized )来判定是否已给原型赋予了任何要领。 操作原型prototype。 function Bar(text, url) { this.text = text; this.url = url; } Bar.prototype = { render : function() { document.write('<a href="' + this.url + '">' + this.text + '</a>'); } } (编辑:湖南网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |