码迷,mamicode.com
首页 > Web开发 > 详细

JS类的实现

时间:2015-09-17 19:36:14      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

1个月前写过,重新写一遍

//类的实现,一个参数创建类,两个参数继承类
var Klass = function (parent, options) {
    var
        hasOwn = Object.prototype.hasOwnProperty,
    //中间函数避免执行父类构造函数
        Func = function () {
        },
    //mixin浅拷贝
        extend = function (receiving, giving) {
            var k;
            for (k in giving) {
                if (hasOwn.call(giving, k)) {
                    receiving[k] = giving[k];
                }
            }
        },
    //返回的子类
        Child = function (opt) {
            extend(this, opt);
        };

    //参数check
    if (arguments.length === 0 || arguments.length > 2) throw new Error("只接受1个或2个参数");
    //只传入一个参数对象
    if (typeof parent !== ‘function‘) {
        options = parent;
        parent = null;
    }
    //继承父类
    if (parent) {
        Func.prototype = parent.prototype;
        Child.prototype = new Func();
        Child.prototype.constructor = Child;
    }
    //添加options
    extend(Child.prototype, options);

    return Child;
};

//测试
var Person = Klass({
        getName: function () {
            return this.name;
        },
        say: function() {
            console.log("hello world");
        },
        fav: ‘Js‘
    }),
    Player = Klass(Person, {
        play: function () {
            console.log("i‘m playing " + this.game);
        }
    }),
    player = new Player({
        name: ‘bobo‘,
        game: ‘Dota2‘
    });

player.play();  // "i‘m playing Dota2"
player.say();   // "hello world"
console.log(player.getName() + " " + player.fav);   //"bobo Js"

 

JS类的实现

标签:

原文地址:http://www.cnblogs.com/coiorz/p/4817087.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!