JavaScript命名空间,类和继承的简单示例

wpe*_*rse 6 javascript inheritance namespaces subclass

我被要求将一些PHP代码移植到JavaScript中,以便我们的更多逻辑在客户端运行.我想要的是一个简单的例子,显示:

  • 包含两个类("Master"和"Slave")的命名空间("Package")
  • "Master"类有一个属性"p",一个函数"m"和一个构造函数,它接受一个参数来设置"p"的初始值
  • "Slave"类继承"p",构造函数和"Master"类中的"m"

我不介意使用某种现有的框架,但它必须是轻量级的 - 理想情况下不超过200 LOC(未缩小).

这是我的尝试,FWIW:

var Package = {};

Package.Master = function(pValue) {
    this.p = pValue;
    this.m = function() {
        alert("mmmmm");
    }
}

Package.Slave = function(pValue) {
    // this will inherit from Package.Master
}

// one of the many online examples:
// http://kevlindev.com/tutorials/javascript/inheritance/index.htm
KevLinDev.extend = function(subClass, baseClass) {
   function inheritance() {}
   inheritance.prototype = baseClass.prototype;

   subClass.prototype = new inheritance();
   subClass.prototype.constructor = subClass;
   subClass.baseConstructor = baseClass;
   subClass.superClass = baseClass.prototype;
}

KevLinDev.extend(Package.Slave, Package.Master);
Run Code Online (Sandbox Code Playgroud)

Mat*_*ott 8

我非常喜欢John Resig的简单Javascript继承.

例如:

var Package = {};
Package.Master = Class.extend({
    init: function(pValue) {
        this.p = pValue;
    },
    m: function() {
        alert("mmmmm");
    }
});

Package.Slave = Package.Master.extend({
    init: function(pValue) {
        this._super(pValue);
    }
});

var slave = new Package.Slave(10);
slave.m();
Run Code Online (Sandbox Code Playgroud)

  • 嘿...是的,昨天遇到了那个网站,因为代码吓到了我而解雇了它.现在只需使用您的代码片段实现它,它就可以了!比我想象的要容易得多......谢谢! (3认同)

Eri*_*ric 5

我认为这是一种方法:

var Package = {};

Package.Master = function(pValue) {
    this.p = pValue;
    this.m = function() {
        alert("mmmmm");
    }
}

Package.Slave = function(pValue) {
    //Call constructor of super class
    Package.Master.call(this, pValue);
}

Package.Slave.prototype = new Package.Master;
Run Code Online (Sandbox Code Playgroud)