`

javascript achieve class like code with closure, prototype and etc...

阅读更多

Javascript is featured of something that is special among other object oriented or object based language, where you do not have class, and there is some mechanism which is called the prototype inheritance that can help you achieve something that fimiliar with most OO programmer. 

 

With object inheritance, it is quite possilbe to simulate the class like code with the use of closures and prototype inheritance.

 

let's first see an example of what will become after we have the class like code implemented.

 

var Person = Object.subClass({

  init: function(isDancing) { 
    this.dancing = isDancing;
  },
  dance : function() {
    return this.dancing
  }
});



var Ninja = Person.subClass({
 init : function() { 

   this._super(false);
 },
 dacne : function() {
   // call hte inherited version of the dance() 
   return this._super();
 },
 swingSword: function() {
   return true; 
 }
});

var n = new Ninja();

assert(n.swingSword(), "Get true, as we expected");
assert(!n.dance(), "The inverse of the super method's value - false.");

// Should all be true 
assert(p instanceof Person && n instance Ninja && n instanceof Person, "the objects inherit functionalities from the correct sources.");

 

 

 

and below is the code that has the library implementation.

 

/**************************************
*@Summary
* With the help of object singleton inheritance, we achieve something that we are faimiliar with in some strong typed language
*
*  this utilize this feature to extend the element in the HTML
*
* @Usage:
*   

var Person = Object.subClass({

  init: function(isDancing) { 
    this.dancing = isDancing;
  },
  dance : function() {
    return this.dancing
  }
});



var Ninja = Person.subClass({
 init : function() { 

   this._super(false);
 },
 dacne : function() {
   // call hte inherited version of the dance() 
   return this._super();
 },
 swingSword: function() {
   return true; 
 }
});

var n = new Ninja();

assert(n.swingSword(), "Get true, as we expected");
assert(!n.dance(), "The inverse of the super method's value - false.");

// Should all be true 
assert(p instanceof Person && n instance Ninja && n instanceof Person, "the objects inherit functionalities from the correct sources.");

* @TODO:
* test it 
***************************************/

/**
*@Comment: class like instance
*   point 1: this is to test the browser compatability. since ew need to test if function can be serialized, if a functin can be serialized, the n
    it is possible to test if the function has used _super

*/

(function () {
  var initializing = false,
  // determine if functions can be serialized 
  // Comment point 1
  fnTest = /xyz/.test(function () { xyz; }) ? /\b_super\b/ : /.*/;
  
  Object.subClass = function (prop) {
    var _super = this.prototype;

    // Initialize a base class (but only create the instantiate,
    // don't run the init constructor
    initializing = true;
    // so given the code sample 
    // var Ninja = Person.subClass(...)
    // this will correspond to the object of 'Person'
    var proto = new this();
    initializing = false;


    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // check if we 're overwriting an existing function
      proto[name] = typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name]) ?
      (function (name, fn) {
        return function () {
          var tmp = this._super;

          // add a new ._super() method that is the same but on the super-class
          this._super = _super[name];

          // the method only need to be bound temporarily, so we remove it when we're done execting 
          var ret = fn.apply(this, arguments);
          this._super = tmp;

          return ret;


        };

      })(name, prop[name]) :
      prop[name];
    }

    // we create a dummy class that can both act as the constructor as well as the class type as well
    function Class() {
      // All construction is actually done in the init method
      if (!initializing && this.init) {
        this.init.apply(this, arguments);
      }
    }

    // populate our constructed prototype objet 
    Class.prototype = proto;

    // Enforce the constructor to be what we expect 
    Class.constructor = Class;


    // and make it extensible so that we can do things like 
    // var Person = Object.subClass(...)
    // var Ninja = Person.subClass(...)
    // and that is because the first Object.subClass() will return Class, and we want to allow user to call
    // subClass further on this function object
    // you need this because it the function's prototype is not directly the Object itself?
    Class.subClass = arguments.callee;

    return Class;
  };
})();
  
 

 

 

and below is the code that we used to test the function. 

 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="classlike.js" type="text/javascript"></script>
    <script src="../unit.js" type="text/javascript"></script>
    <script type="text/javascript">
      window.onload = function () {

        test("classlike test", function () { 

          var Person = Object.subClass({
          init: function(isDancing) { 
            this.dancing = isDancing;
          },
          dance: function() {
            return this.dancing
          }
          });

        var Ninja = Person.subClass({
         init : function() { 

           this._super(false);
         },
         dacne : function() {
           // call hte inherited version of the dance() 
           return this._super();
         },
         swingSword: function() {
          return true;
         }
        });

        var n = new Ninja();

        assert(n.swingSword(), "Get true, as we expected");
        assert(!n.dance(), "The inverse of the super method's value - false.");

        // Should all be true 
        assert(p instanceof Person && n instanceof Ninja && n instanceof Person, "the objects inherit functionalities from the correct sources.");
      }
   );
        
};
    </script>
    <style type="text/css">
      #results li.pass { color: Green }
      #results li.fail { color: Red }
    </style>
</head>
<body>
<ul id="results" />
</body>
</html>
 

 

 

分享到:
评论

相关推荐

    Closure The Definitive Guide

    Compiler, Templates, testing framework, and Inspector -- including how to minify JavaScript code with the Compiler, and why the combination of the Compiler and the Library is what sets Closure apart ...

    javascript语言精粹(中英文版)

    Prototype Section 3.6. Reflection Section 3.7. Enumeration Section 3.8. Delete Section 3.9. Global Abatement Chapter 4. Functions Section 4.1. Function Objects Section 4.2. Function Literal ...

    JavaScript闭包(closure).pdf

    JavaScript闭包(closure).pdf

    closure-compiler-v20190819.jar

     –js:javascript文件名,可以指定多个   –js_output_file:主要输出文件,如果没有指定,压缩后的文件将用标准输出输出   –compilation_level[WHITESPACE_ONLY | SIMPLE_OPTIMIZATIONS 

    串口通讯控件

    - Corrected bugs which caused occasional crashes on port closure. - Corrected bugs which caused unnecessary exceptions when sending data at low baud rates with CheckAllSends = false. - Fixed ...

    理解javascript函数式编程中的闭包(closure)_.docx

    理解javascript函数式编程中的闭包(closure)_.docx

    nodejs中文学习手册

    2 JavaScript 與 NodeJS 11 2.1 Event Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.2 Scope 與 Closure . . . . . . . . . . . . . . . . . . . . . . . . . . 12 2.3 Callback . . . ...

    Google Javascript Closure Compiler

    closure-compiler-v20170521.jar,以及一个.chm使用说明:‘Getting Started with the Closure Compiler Application’,‘Advanced Compilation and Externs’,‘Understanding the Restrictions Imposed by the ...

    RTL Coding and Optimization Guide for use with Design Compiler.pdf

    fixed with placement – the designer has to go back to their RTL code and re-write it to fix the problem. Code it correctly from the beginning, anticipating implementation roadblocks and barriers, ...

    Javascript Closure

    Closure: the definitive guide, by Michael Bolin

    Bulletproof SSL and TLS,PDF , Ivan Ristic

    Bulletproof SSL and TLS by Ivan Ristić Table of Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...

    Closure-Table-ClosureTable.rar

    主要完成了数据库存储概念中Closure-Table 存储,写了一个SSM简单的项目 项目是github上的,github也是我自己的项目

    closure dependency not found解决包

    当我们从github上下载了blockly之后,打卡demos下的index.html时,选择blockly-developer-tools时会弹出一个对话框(大体内容是closure dependency not found),此时我们需要下载这个文件,解压并且命名为closure-...

    非常好的javascript原理资源,分享出来.zip

    javascript Javascript 代码 其中很多都是伪代码的写法,便有回顾和总结。参考资料 包含 javascript 的基础语法 面向对象的实现 设计模式实现 模块化开 javascript 常见的疑问 jQuery NodeJs html5 Javascript ...

    Skiena-The_Algorithm_Design_Manual.pdf

    4.5 Mergesort: Sorting by Divide-and-Conquer . . . . . . . . . . . . 120 4.6 Quicksort: Sorting by Randomization . . . . . . . . . . . . . . . 123 4.7 Distribution Sort: Sorting via Bucketing . . . . ...

    Closure Library

    The Closure Library is a broad, well-tested, modular, and cross-browser JavaScript library. You can pull just what you need from a large set of reusable UI widgets and controls, and from lower-level ...

    Google_Closure官方教程中文版.pdf

    Google_Closure官方教程中文版.pdf

    closure-compiler-v20171112.jar

    google closure compiler js混淆压缩工具方便无法访问google的朋友们下载

    Service Support-英文原版

    1.8 Customers and Users....................................................................................................- 10 - 1.9 A Code of Practice for IT Service Management – PD0005...............

    javascript prototype,executing,context,closure

    要学好JavaScript,有几个基本概念必须搞清楚:prototype,executing,context,closure。Prototype 在JavaScript语言中,通常使用Prototype来实现OO。在这里,我们不对JavaScript的OO实现进行过多的探讨,着重来看...

Global site tag (gtag.js) - Google Analytics