//使用this关键字定义构造的上下文属性 function girl() { this.name = "big pig"; this.age = 20; this.standing; this.bust; this.waist; this.hip; } //使用prototype function girl(){} girl.prototype.name = "big pig"; girl.prototype.age = 20; girl.prototype.standing; girl.prototype.bust; girl.prototype.waist; girl.prototype.hip; alert(new girl().name);
上例中的两种定义在本质上没有区别,都是定义“girl”对象的属性信息。“this”与“prototype”的区别主要在于属性访问的顺序。如:
function test() { this.text = function() { alert("defined by this"); } } test.prototype.test = function() { alert("defined by prototype"); } var _o = new test(); _o.test();//输出“defined by this”
当访问对象的属性或者方法是,将按照搜索原型链prototype chain的规则进行。首先查找自身的静态属性、方法,继而查找构造上下文的可访问属性、方法,最后查找构造的原型链。
“this”与“prototype”定义的另一个不同点是属性的占用空间不同。使用“this”关键字,示例初始化时为每个实例开辟构造方法所包含的所有属性、方法所需的空间,而使用“prototype”定义,由于“prototype”实际上是指向父级的一种引用,仅仅是个数据的副本,因此在初始化及存储上都比“this”节约资源。
以上就是javascript自定义对象构造的方式实例详解的详细内容。
