prototype
函数被创建的时候,会自动生成一个prototype对象,一个预设对象属性
//定义所有实体都能公用的属性
function Person(name,age){
//...
}
Person.prototype.hi = function(){}
function Student(name,age,className) {
Person.call(this,name,age);
this.calssName = className;
}
//为了使继承后的Student上的prototype不影响Person上的prototype,用Object.create()
Student.prototype=Object.create(Person.prototype);//创建一个空对象,原型指向Person的prototype
Student.prototype.constructor=Student; //不然会指向Person
//修改prototype的属性,会影响到在这之后的对象,不会影响到之前的
foo.prototype.z=3;
'z' in obj;//会追溯到原型
obj.hasOwnProperty('z');//只查看本类
instanceof
instanceof比较两边是否有一样的prototype
调用基类:
//call
Person.prototype.init = function(){};
Student.prototype.init=function() {
Person.prototype.init.apply(this,argument);
}
链式调用
function ClassManager(){}
ClassManager,prototype.addClass = function(str) {
//...
}
var manager = new ClassManager();
manager.addClass().addClass().ddClass();
实践:
!function(global) {
function DetectorBase(configs) {
if(!this instanceof DetectorBase) {
throw new Error('Do not invoke without new');//防止不new就直接调用类
}
this.configs = configs;
this.analyze();
}
}
DetectorBase.prototype.detect = function() {
throw new Error('Not implemented');//由于基类不是具体的探测器,所以需要子类继承实现,基类不实现
};
DetectorBase.prototype.analyze = function() {
console.log('analyzing');
this.data = "###data###";
};
}
function LinkDetector(links) {
if(!this instanceof LinkDetector) {
throw new Error('Do not invoke without new');
}
this.links = links;
DetectorBase.apply(this,arguments);
}
function ContainerDetector(contaniers) {
if(!this instanceof ContainerDetector) {
throw new Error('Do not invoke without new.');
}
this.containers = containers;
DetectorBase.apply(this,aguments);
}
//继承
inherit(LinkDetector, DetectorBase);
inherit(ContainerDetector, DetectorBase);
LinkDetector.prototype.detect = function() {
console.log('Loading data:'+this.data);
console.log('Link detection started.');
console.log('Scaning links' + this.links);
};
ContainerDetector.prototype.detect = function() {
console.log('Loading data:'+this.data);
console.log('Container detection started.');
console.log('Scaning containers'+this.containers);
};
Object.defineProperties(global,{//其余属性都是false
linkDetector:{value:LinkDeteor},
ContainerDetector:{value:ContainerDetector},
DetectorBase:{value:DetectorBase}
});
function inherit(subClass,superClass) {
subClass.protptype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
}
Object.freeze(DetectBase);
Object.freeze(DetectBase.prototype);
Object.freeze(LinkDetector);
Object.freeze(LinkDetector.prototype);
Object.freeze(ContainerDetector);
Object.freezeContainerDetector.prototype);
}(this);
var cd = new ContainerDetector('#abc #def #ghi');
var id = new LinkDetector('http://www.taobao.com');
cd.detect();
id.detect();