zoukankan      html  css  js  c++  java
  • javascript:inheritance(1)

    伪类

    //构造器调用模式
    var Mammal = function (name)
    {
    this.name = name;
    };
    Mammal.prototype.get_name
    = function()
    {
    return this.name;
    };
    Mammal.prototype.says
    = function ()
    {
    return this.saying || '';
    };
    var Cat = function(name)
    {
    this.name = name;
    this.saying = 'meow';
    };
    Cat.prototype
    = new Mammal();
    Cat.prototype.purr
    = function(n){
    var i, s = '';
    for(i = 0; i < n; i ++)
    {
    if(s)
    {
    s
    += '-';
    }
    s
    += 'r';
    }
    return s;
    };
    Cat.prototype.get_name
    = function()
    {
    return this.says() + ' ' + this.name + ' ' + this.says();
    };

    var myCat = new Cat('Henrietta');
    var says = myCat.says();
    var purr = myCat.purr(5);
    var name = myCat.get_name();

    //上面的伪类模式看起来很奇怪,我们可以隐藏一些丑陋的细节。
    //使用method方法定义一个inherits方法来实现

    Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
    return this;
    };
    Function.method(
    'inherits', function(Parent){
    this.prototype = new Parent();
    return this;
    });
    var Cat = function(name)
    {
    this.name = name;
    this.saying = 'meow';
    }.inherits(Mammal).method(
    'purr',function(n){
    var i, s = '';
    for(i = 0; i < n; i ++)
    {
    if(s)
    {
    s
    += '-';
    }
    s
    += 'r';
    }
    return s;
    }).method(
    'get_name', function(){
    return this.says() + ' ' + this.name + ' ' + this.says();
    });

    //以上代码有类似于“类”的构造器函数,但是它没有私有环境,所有属性都是公开的。无法访问父类的方法。
    //而且如果调用的时候没有用new,那么this将被绑定到全局对象上,所以不但没有扩充新对象,反而破坏了全局变量。

  • 相关阅读:
    正则表达式(二):Unicode诸问题(上)
    ANT Notes
    Linux下OpenGL开发 -- 准备篇 (转)
    两个和尚
    Office 2008 for Mac 安装笔记
    从软件工程师到IT猎头:我的一点经历和感触 (转)
    One splitpath implementation (platform independent)
    ANT的使用(转)
    80后中专毕业奋斗10年 我的理财选择
    用ANT来实现邮件发送
  • 原文地址:https://www.cnblogs.com/RitaRichard/p/2111926.html
Copyright © 2011-2022 走看看