
proto
- 每个对象具有的属性,指向构造该对象的构造函数的原型对象
prototype
- 函数的特有属性,指向原型对象;原型对象可以是对象,数组,函数等类型;
constructor
- 原型对象和实例,都有一个属性
constructor
,指回原构造函数
- 修改实例的
constructor
不会直接切断和原构造函数联系;
- 修改实例的
__proto__.constructor
(即原型对象的constructor
)会切断生成实例和原构造函数联系;
类风格的代码
//可以构建新构造器函数和原型的轻量级系统
//简单的方式来执行原型继承
//可以访问被函数原型所覆盖的方法的途径
(function () {
var initializing = false,
//测试函数是否能被序列化,判断函数是否包含_super
superPattern = /xyz/.test(function() {xyz;}) ? /_super/ : /.*/;
Object.subClass = function (properties) {
//上级的prototype
var _super = this.prototype
//初始化超类
//原型实例化时设置为true
initializing = true
var proto = new this()
initializing = false
//将属性复制到prototype里
for (var name in properties) {
//考虑父类的函数
proto[name] = typeof properties[name] == 'function' && typeof _super[name] == 'function' && superPattern.test(properties[name]) ?
(function (name, fn) {
//包装执行子类函数,同时可以通过_super访问父类函数
return function () {
var tmp = this._super
this._super = _super[name]
var ret = fn.apply(this, arguments)
this._super = tmp
return ret
}
})(name, properties[name])
: properties[name]
}
//类构造器
function Class() {
if(!initializing && this.init) {
this.init.apply(this, arguments)
}
}
Class.prototype = proto;
Class.constructor = Class;
Class.subClass = arguments.callee;
return Class
}
})()
//使用
var Person = Object.subClass({
init: function (isDancing) {
this.dancing = isDancing
},
dance: function () {
return this.dancing
}
})
var Ninja = Person.subClass({
init: function () {
this._super(false);
},
dance: function () {
return this._super()
},
swingSword: function () {
return true
}
})
var person = new Person(true)
var ninjia = new Ninja()