原生Javascript类实现

时间:2010-08-05 18:20:23

标签: javascript class inheritance

我目前参与了一个Web应用程序项目,我们不打算使用框架。

我正在寻找'最佳'的javascript继承实现。我使用过原型样式课程如下:

function animal(options) {
    self = this;

    //properties    
    this.name = options.name;

    //events

    this.onXYZ = options.onXYZ;

    //event handlers
    this.handlerOfEvent = function() {
        //do something using 'self' as the 'this' variable
    }
}

animal.prototype.aFunction = function() 
{
     //do something 
}

我没有使用没有框架的继承(通常使用Mootools),但我确实理解它在Javascript中是如何工作的,并且已经看到了很少的实现。

我希望得到一些关于我能找到最佳实现的反馈,一个不会使用任何本机类型的反馈,并允许我完全访问上升类的属性和函数。

任何指针都会非常感激。

非常感谢你的时间。

4 个答案:

答案 0 :(得分:1)

道格拉斯·克罗克福德(道格拉斯·克罗克福德)描述的方法是我最近偏爱的方法:

var rectangle = function(width, height)
{
    var h = height, w = width;
    var scale = function(s)
    {
        h = h * s;
        w = w * s;
    }

    return { scale: scale };
}

var square = function(width)
{
    var o = rectangle(width, width)
    // Add things to o, if needed
    return o;
}

不是一个非常好的例子,因为没有任何东西真正被扩展,但它应该得到这个想法。要实例化这些对象,只需使用:

var newRectangle = rectangle(3, 4);  // 3 by 4 rectangle
var newSquare = square(6);  // 6 by 6 square

答案 1 :(得分:0)

我过去尝试了很多方法。我最喜欢John Resig的实施方式。这很简单。您可以在http://ejohn.org/blog/simple-javascript-inheritance/

中看到完整的示例和javascript文件(只有大约25行代码)

为了完成答案,你可以在包含他的代码之后实现这样的类..

var Person = Class.extend({
    name : '',
    init : function (name) {
        this.name = name;
    },
    say : function () {
        alert("I'm " + this.name);
    }
});

var mick = new Person("Mick");
mick.say();

答案 2 :(得分:0)

查看Simple Javascript Class Project(常量,属性,受保护,静态,实用程序等),Simple JavaScript InheritanceInheritance Patterns in JavaScript

简单Javascript类(sjsClass)示例

Class.extend('Foo', {
    __protected : {
        privV : 123,
        privF : function () {
            return this.privV + this.priv3;
        }
    },
    'protected priv3' : 'Protected Value',
    setX : function (x) {
        this.privV = x;
    },
    test : function () { return this.privF(); }
});
var f = new Foo;
f.setX(456);
f.test(); // -> 'Protected Value456'
f.privF(); // -> Error
f.privV; // -> undefined
f.priv3; // -> undefined

答案 3 :(得分:-1)

你应该检查道格拉斯克罗克福德的videos关于“寄生遗传”的内容。

这是一个基本的例子

    var pkg={};//simulating a package
    pkg.ObjA=function (){
    var privateField;//every inner function will have a closure to this field, this is the way to simulate private fields
    var privatefunc=function(){
    //same for private functions
    };
    //use object augmentation to add different fields to the "that" reference
    that.publicMethod=function(){
    //do something
    };
    return that;
    }

    //create two different instance of the object A
    var instance1=pkg.ObjA();
    var instance2=pkg.ObjA();

pkg.ObjB=function(){

//the that of this object is based on the ObjA
var that=pkg.ObjA();

//specialize the that to simulate inheritance
that.newMethod=function(){

}
return that;
}

var child=pkg.ObjB();