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将被绑定到全局对象上,所以不但没有扩充新对象,反而破坏了全局变量。

  • 相关阅读:
    Log4Net使用指南
    构建Asp.Net2.0 GridView复合多层表头的几种方法
    javaScript中如何定义类
    是不是silverlight 2 的bug
    领悟 JavaScript 中的面向对象
    web拖动Drag&amp;Drop原理
    一个不错的js验证框架
    MySQL中文参考手册
    高效实现数据仓库的七个步骤
    什么是ARP?如何防范ARP欺骗?
  • 原文地址:https://www.cnblogs.com/RitaRichard/p/2111926.html
Copyright © 2011-2022 走看看