zoukankan      html  css  js  c++  java
  • Javascript设计模式系列三

      继承,一个类或对象继承另一个类或对象的三种方法。类式继承、原型式继承、掺元类。

      一、类式继承,原型链、Extend函数。

     <script type="text/javascript">
            
            ////定义Person类
            var Person = function (name) {
                this.name = name;
            };
    
            Person.prototype.getName = function () {
                return this.name;
            };
    
            ////原型链
            function Author(name, books) {
                Person.call(this, name);
                this.books = books;
            };
    
            Author.prototype = new Person();
            Author.prototype.constructor = Author;
            Author.prototype.getBooks = function () {
                return this.books;
            };
    
            var author = new Author("XX", "books")
            alert(author.getName()+author.getBooks());
    
            ////Extend函数
            function Extend(subClass,superClass) {
                var F = function () { };
                F.prototype = superClass.prototype;
                subClass.prototype = new F();
                subClass.prototype.constructor = subClass;
            };
    
            function Author(name, books) {
                Person.call(this, name);
                this.books = books;
            }
    
            Extend(Author, Person);
    
            Author.prototype.getBooks = function () {
                return this.books;
            };
    
            var author = new Author("X", "books")
            alert(author.getName() + author.getBooks());
    
        </script>

      二、原型式继承。使用原型式继承时,并不需要用类来定义对象的结构,只需直接创建一个对象即可。这个对象随后可以被新的对象重用,该对象被称为原型对象。Clone函数。

     <script type="text/javascript">
    
            ////Clone函数
            function clone(object) {
                function F() { };
                F.prototype = new object();
                return new F();
            };
    
            ////定义Person类
            var Person = function () {
                this.name = 'default name';
                this.getName = function () {
                    return this.name;
                }
            };
    
            ////实例化
            var Author = clone(Person);
            alert(Author.name);
            Author.name = "原型式继承";
            alert(Author.name);
            alert(Author.getName());
     
        </script>

      三、掺元类,一个函数用到多个类中,可以使用扩充的方式让这些类共享该函数。

      本文源于:Javascript设计模式。

  • 相关阅读:
    mac 鼓捣php 多版本切换
    thinkPHP 导出excel 发布正式环境net::ERR_INVALID_RESPONSE
    js 计时显示 倒着 正者 都行
    LNMP 下 php.ini 文件修改后不生效
    Jquery 遍历数组之$().each方法与$.each()方法介绍
    js 去掉字符串最后一个逗号
    js拼接字符串时,字符串首出现undefined的问题
    PHP 暂停函数 sleep() 与 usleep() 的区别
    在IDEA里创建web项目,以及web 项目部署
    spring容器和springmvc容器,以及web容器的关系
  • 原文地址:https://www.cnblogs.com/zhang-lei/p/4102569.html
Copyright © 2011-2022 走看看