apply 高级应用

1.实现类"继承"(将一个类的成员复制给一个对象)

function Rectangle()
{
    this.width = 0;
    this.height = 0;
    this.area = function(){ return this.width * this.height;};
}

var o = new Object();
Rectangle.apply(o);
o.width = 10;
o.height = 20;
alert(o.area());

调用apply时,o对象就是Rectangle函数中this的值,因而实现了属性的复制。

2.给类设置初始化函数

var Class = {
    create : function(){
        return function(){
            this.initialize.apply(this,arguments);
        }
    }
}

//创建类
var Rectangle = Class.create();
Rectangle.prototype = {
    initialize : function(width,height){
        this.width = width;
        this.height = height;
    },
    toString : function(){
        return "width:" + this.width + "\r\n" + "height:" + this.height;
    }
}

//实例化对象并初始化
var rectangle = new Rectangle(80,120);
alert(rectangle.toString());


上一篇: 理解 JavaScript 闭包
下一篇: Javascript作用域原理
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags:
最新日志:
评论: 0 | 引用: 0 | 查看次数: 3650
发表评论
登录后再发表评论!