`

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 ...

    closure-compiler-v20171112.jar

    Closure Compiler是Google开发的一款强大的JavaScript代码优化工具,其主要功能是对JavaScript代码进行压缩和混淆,以提高代码的运行效率和安全性。"closure-compiler-v20171112.jar"是该编译器的一个特定版本,发布...

    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 ...

    串口通讯控件

    - 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 ...

    Closure-Table-ClosureTable.rar

    Closure Table 是数据库设计中一种处理层次结构数据的方法,主要用于存储具有层级关系的数据,例如组织架构、类别层次等。在这个名为 "Closure-Table-ClosureTable.rar" 的项目中,开发者使用了Spring、SpringMVC...

    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, ...

    PROTOTYPE 1.5.1 RC1

    3. **AJAX支持**:Prototype提供了强大的AJAX(Asynchronous JavaScript and XML)功能,如`Ajax.Request`和`Ajax.Updater`,它们允许开发者创建异步交互的应用,无需刷新页面就能与服务器交换数据并更新页面内容。...

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

    本篇文章主要探讨JavaScript函数式编程中的一个重要概念——闭包(closure)。闭包是一种特殊的函数,它能记住其定义时的作用域,即使在函数执行完毕后,仍然可以访问到该作用域内的变量。在JavaScript中,每个函数...

    closure library 模块化的javascript库

    Closure Library是Google开发的一个强大的、模块化的JavaScript库,旨在提供高效、可维护的代码解决方案。这个库被设计为可跨浏览器、跨平台使用,确保在各种JavaScript环境中的一致性。Closure Library的核心理念是...

    javascript 必知必会之closure

    下面的代码片断缩进目前还不完善,你也可以选择 下载pdf 来...A “closure” is an [removed]typically a function) that can have free variables together with an environment that binds those variables (that

    JavaScript闭包(closure).pdf

    JavaScript中的闭包是一种高级特性,它是函数和其周围状态(词法作用域)的组合,即使函数在其定义的作用域之外被调用,它仍然能访问到这些状态。这个概念是JavaScript编程中的核心部分,尤其在处理异步操作、模块化...

    Bulletproof SSL and TLS,PDF , Ivan Ristic

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

    Myclassroom教学设计焦雨昕.docx

    StepⅣ Summary and closure1: Review the key words and phrases from the lesson, emphasizing their usage in context. This helps solidify the new language in students' minds. 2: Ask students to share ...

    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 dependency not found解决包

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

    Closure编译器的纯JavaScript版本最高级的构建工具

    Closure编译器是Google开发的一款强大的JavaScript优化工具,它的纯JavaScript版本为开发者提供了一种高效、先进的代码构建方案。此工具旨在提升JavaScript代码的质量、性能和可维护性,通过压缩、优化以及处理代码...

Global site tag (gtag.js) - Google Analytics