代码分析:
var materialId = 0;
function Material() {
Object.defineProperty( this, 'id', { value: materialId ++ } );
this.uuid = MathUtils.generateUUID();
this.name = '';
this.type = 'Material';
}
Material.prototype.test = function(){
}
function SpriteMaterial( parameters ) {
Material.call( this );
this.type = 'SpriteMaterial';
this.color = new Color( 0xffffff );
this.map = null;
this.alphaMap = null;
this.rotation = 0;
this.sizeAttenuation = true;
this.transparent = true;
this.setValues( parameters );
}
SpriteMaterial.prototype = Object.create( Material.prototype );
SpriteMaterial.prototype.constructor = SpriteMaterial;
SpriteMaterial.prototype.isSpriteMaterial = true;
解析:
1、Material和SpriteMaterial都是Function创建出来的函数对象,这两个函数对象中的this都是其new Material()和new SpriteMaterial()之后的Object对象。
2、对于上面代码这个继承过程,首先在SpriteMaterial中调用Material.call( this );这个说明如果let sp = new SpriteMaterial时会将Material、SpriteMaterial中的this都指向sp这个对象。
3、SpriteMaterial.prototype = Object.create( Material.prototype )这个过程会将Material.prototype的原型拷贝一份,防止后续SpriteMaterial.prototype上添加成员是修改Matieral.prototype。
4、SpriteMaterial.prototype.constructor = SpriteMaterial;将构造函数重新指向了自身,就是在new SpriteMaterial的时候会调用constructor构造函数。
5、SpriteMaterial.prototype.isSpriteMaterial = true; 在原型的基础上增加了新的属性,虽有对象的实例都会添加这个属性。