Last active
December 15, 2015 23:09
-
-
Save kampfer/5338083 to your computer and use it in GitHub Desktop.
Klass in <Javascript Patterns>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var klass = function(Parent, props) { | |
var Child, F, i; | |
//调用'子类'的构造函数时,'父类'的构造函数也会被调用 | |
Child = function() { | |
if( Child.uber && Child.uber.hasOwnProperty('__construct') ) { | |
Child.uber.__construct.apply(this, arguments); | |
} | |
if( Child.prototype.hasOwnProperty('__construct') ) { | |
Child.prototype.__construct.apply(this, arguments); | |
} | |
}; | |
//默认的'父类': Object | |
Parent = Parent || Object; | |
//F的作用是:避免Child和Parent共享同一个原型,造成干扰. | |
//修改'父类'会影响'子类'但是修改'子类'不会影响'父类' | |
F = function() {}; | |
F.prototype = Parent.prototype; | |
Child.prototype = new F(); | |
//保存到'父类'的引用. | |
Child.uber = Parent.prototype; | |
Child.protptype.constructor = Child; | |
for(i in props) { | |
if( props.hasOwnProperty(i) ) { | |
//由于F的存在, 这里的修改不会影响Parent | |
Child.prototype[i] = props[i]; | |
} | |
} | |
return Child; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment