JavaScript继承设计机制
suoyuesmile opened this issue · 1 comments
suoyuesmile commented
JavaScript继承设计机制
suoyuesmile commented
- 引入new命令并简化类直接使用构造函数
function DOG(name) {
this.name = name;
}
var dog = new DOG('大毛');
alert(dog.name);
- 构造函数无法共享变量引入prototype属性
- 为构造函数设置属性prototype,这个属性包含一个对象
- 需要共享的属性方法放这个对象中,不需要共享的放构造函数中
- 对象一旦创建自动引用prototype对象的属性和方法,实例的对象一共两种,一种本地,一种引用
function DOG(name) {
this.name = name;
}
DOG.prototype = { species : '猫科'};
var dog = new DOG('大毛');
var dog1 = new DOG('二毛');
alert(dog.species);
alert(dog1.species);
所有实例共享一个prototype对象,prototype对象就好像实例对象的原型,而实例对象则好像继承了prototype对象一样