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设计模式。

  • 相关阅读:
    Hive数据倾斜原因和解决办法(Data Skew)
    Hive简介
    SQL---公共表表达式(CTEs)
    SQL面试题---topN问题
    SQL---分页查询
    SQL---自连接(self join)
    SQL---关联子查询(correlated subquery)
    SQL---CASE表达式
    SQL查询语句执行顺序
    SQL---窗口函数(window function)
  • 原文地址:https://www.cnblogs.com/zhang-lei/p/4102569.html
Copyright © 2011-2022 走看看