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

  • 相关阅读:
    URL传递的参数是UTF-8编码,在打开的页面正常显示(GB2312)的方法
    JS windows.open打开窗口并居中
    一个tomcat如何部署多个项目运行
    redis 服务配置开机自启动
    解决端口被占用问题
    MySQL中concat以及group_concat的使用
    java 使用OpenOffice文件实现预览
    eclipse安装maven插件
    数据库三范式
    mysql 查询的字段值太长显示不全 group_concat
  • 原文地址:https://www.cnblogs.com/RitaRichard/p/2111926.html
Copyright © 2011-2022 走看看