首页 > 代码库 > Class 类

Class 类

在javascript 中应用类的概念

// javascript web applications 富应用开发// 类库:生成类的地方;给所有的构造函数提供基础方法,如 extend, include...var Class = function () {        var klass = function () {        // 实例化对象时立即运行init函数        this.init.apply(this, arguments);    };    klass.prototype.init = function () {};    // 定义 prototype 的别名    klass.fn = klass.prototype;    // 给类添加属性    klass.extend = function (obj) {        var prop;        for (prop in obj) {            klass[prop] = obj[prop];        }    };    // 给实例添加属性    klass.include = function (obj) {        var prop;        for (prop in obj) {            klass.fn[prop] = obj[prop];        }    };    return klass;  // 仍然返回一个类};// new 一个类var Person = new Class();/*  * 初始化方法(生成实例的时候一定会运行的方法) * * 等同于: * * var Person = function (name) { *    this.name = name; * };*/Person.prototype.init = function (name) {    this.name = name;};// 原型方法Person.include({    say: function () {        console.log(this.name + " say hello to everyone!");    }});var person = new Person("Davi");person.say();  // Davi say hello to everyone!

 

用 backboon.js 实现类

/* * <script src="http://www.mamicode.com/js/underscore-1.6.0.js"><\/script> * <script src="http://www.mamicode.com/js/backbone-1.1.2.js"><\/script> * * backboon.js 是一个 MVC 框架 * 重度依赖 underscore.js*/// 用 backbone 框架实现类var Person = Backbone.Model.extend({    initialize: function (attr) {        var prop;        for (prop in attr) {            this[prop] = attr[prop];        }    },    say: function () {        console.log(this.name + " is " + this.age + " years old.");    }});// 类的原型继承:即父类的扩充var Student = Person.extend({    study: function () {        console.log("good good study!");    }});// 实例化的时候执行了 initialize 初始化函数var s = new Student({    name: "Davi",    age: "20"});// Person 的 say 方法;Student 的 study 方法。s.say();    // Davi is 20 yeas old.s.study();  // good good study!