您的位置:首页 > Web前端 > JavaScript

javascript类式继承函数最优版

2013-10-16 22:56 288 查看
直接上代码:

klass函数

var klass = function (Parent, props) {
var Child, F, i;

//1.新构造函数
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);
}
};

//2.继承
Parent = Parent || Object;
F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.uber = Parent.prototype;
Child.prototype.constructor = Child;

//3.添加实现方法
for (i in props) {
if (props.hasOwnProperty(i)) {
Child.prototype[i] = props[i];
}
}

//返回该class
return Child;
};


使用实例:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>类式继承</title>
<script src="klass.js"></script>
</head>
<body>
<script>
var Man = klass(null, {
__construct : function (name) {
console.log("Man's constructor!");
this.name = name;
},
getName : function () {
return this.name;
}
});

//var first = new Man('Adam');
//console.log(first.getName());

var SuperMan = klass(Man, {
__construct : function (name) {
console.log("SuperMan's constructor!");
},
getName : function () {
var name = SuperMan.uber.getName.apply(this);
return "I am " + name;
}
});

var clark = new SuperMan('Clark Kent');
console.log(clark.getName());

</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: