Class 创建类

使用Class.create()创建类

function createClass()
{
    var Car=Class.create();
    Car.prototype={
    initialize:function (owner,color)//initialze是构造函数
    {
        this.Owner=owner;//属性
        this.Color=color;
        alert("Construnctor Function :\n"+Car);
    },
    sayColor:function ()
    {
        alert("My Color is "+this.Color);//this指向调用该函数的对象
    },
    sayOwner:function ()
    {
        alert("My Owner is "+this.Owner);
    }
};

var myCar =new Car("Hafeyang","Silver");
myCar.sayColor();
}
//Prototype中的所有的类都是通过上述方法创建的,然后利用Object.extend方法实现扩展

//以下是常规的通过原型方式构造类的方法,在这里可以发现两者非常相似
function createClass2()
{
    function Car(owner,color)
    {
        this.Owner=owner;
        this.Color=color;
        alert("Construnctor Function :\n"+Car);
    }
    Car.prototype={
        sayColor:function ()
        {
            alert("My Color is "+this.Color);
        },
        sayOwner:function ()
        {
            alert("My Owner is "+this.Owner);
        }
};

var myCar =new Car("Hafeyang","Silver");
myCar.sayColor();

Object.extend()扩展javascript事例

Object.extend = function(destination, source) {
    for (var property in source) {
    destination[property] = source[property];
    }
    return destination;
}

Object.extend(Object, {
    inspect: function(object) {
    try {
            if (object === undefined) return 'undefined';
            if (object === null) return 'null';
            return object.inspect ? object.inspect() : object.toString();
        } catch (e) {
        if (e instanceof RangeError) return '...';
          throw e;
}
});
//上面的例子就实现了Object.inspect()方法