`

javascript subclassing native objects

阅读更多

You can subclass native object, the most often sub-classed object is the Object class itself. 

 

Let's first see some cases that you do with sub-classing the object class. 

 

 

Object.prototype.keys1 = function () {
  var keys1 = [];
  for (var i in this) {
    keys1.push(i);
  }
  return keys1;

};
 

 

However, the gotchas above is that when you call keys1(), it may returns more properties than youmight expect it to returns. let's see the example below.

 

 

          var obj = { a: 1, b: 2, c: 3 };
          assert(obj.keys1().length != 3, "The 3 existing properties plus the new keys method keys1, and others");
 

 

so you might take care of which properties are on the actual object rather than on inherited prototyped object.

 

 

Below is the improved version.

 

 

Object.prototype.keys = function () {
  var keys = [];
  for (var i in this) {
    if (this.hasOwnProperty(i)) {
      keys.push(i);
    }
  }
  return keys;
};
 

 

And below is the test code 

 

 

          var obj = { a: 1, b: 2, c: 3 };
          assert(obj.keys().length == 3, "Only the 3 exiting properties are included.");
 

 

 

Extending the Array.

 

 

due to some reason, the IE does not support directly sub-classing the Array, because the property of length of Array is immutable. but  you can take the following workaround.

 

 

/**
* @MyArray now fake the interface of Array, but it does not inherit from Array directly now.
*/
function MyArray() { }
// this length property is to simulate the Array length property, of which is essential to simulate native array object

MyArray.prototype.length = 0;

(function () {
 var methods = ['push', 'pop', 'shift', 'unshift', 'slice', 'splice', 'join'];

  for (var i = 0; i < methods.length; i++) { 
    (function(name) { 
       MyArray.prototype[name] = function() { 
         return Array.prototype[name].apply(this, arguments);
       };
    })(methods[i]);
  }
})();

 

 

and then you can do the test via the following code. 

 

 

          var mine = new MyArray();

          mine.push(1, 2, 3);
          assert(mine.length == 3, "All the items are on our sub-classed array.");
          assert(!(mine instanceof Array), "We are sub-classing array, though");
 

 

 

Extending numbers

 

 

You might think you can override the number class so that you can add extra functions to the function literal; However, this is not always true, because of the way how the Javascript engine parse numbers and its properties of the number, it might not work as you expected, as illustrated in the following example. 

 

 

 

Number.prototype.add = new function (num) {
  return this + num;
}
 

 

 

 

and the following code shows the tests and its results.

 

 

          var n = 5;
          assert(n.add(3) == 8, "It works fine if the number is an varaible.");
          alert((5).add(3) == 8, " Also works if a number is wrapping in parenthesis.");
  

 

Following is the full code. 

 

/**************************************
*@Summary
* This shows how you can subclass some native object from javascript
*
*  this utilize this feature to extend the element in the HTML
*
* @Usage:
*   


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

/** 
* First attempt to subclass the native Array object
*
* @Comment: there are some restriction by the IE explorer in that it simply does not allow the Array type to be inherted, the reason is becaue the length property is immutable
*/
//function MyArray() { }

//MyArray.prototype = new Array();

//var mine = new MyArray();
//mine.push(1, 2, 3);

//assert(mine.length == 3, "All the items are on our sub-classed array.");
//assert(mine instanceof Array, "Verify that we implement Array functionality.");


Object.prototype.keys1 = function () {
  var keys1 = [];
  for (var i in this) {
    keys1.push(i);
  }
  return keys1;

};

Object.prototype.keys = function () {
  var keys = [];
  for (var i in this) {
    if (this.hasOwnProperty(i)) {
      keys.push(i);
    }
  }
  return keys;
};



/**
* @MyArray now fake the interface of Array, but it does not inherit from Array directly now.
*/
function MyArray() { }
// this length property is to simulate the Array length property, of which is essential to simulate native array object

MyArray.prototype.length = 0;

(function () {
 var methods = ['push', 'pop', 'shift', 'unshift', 'slice', 'splice', 'join'];

  for (var i = 0; i < methods.length; i++) { 
    (function(name) { 
       MyArray.prototype[name] = function() { 
         return Array.prototype[name].apply(this, arguments);
       };
    })(methods[i]);
  }
})();



Number.prototype.add = new function (num) {
  return this + num;
}
 

 

 

and its harnessed test.

 

 

<!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 type="text/javascript" src="../unit.js"></script>
    <script type="text/javascript" src="subclassnative.js"></script>
    <script type="text/javascript">

      var mine = new MyArray();
      mine.push(1, 2, 3);


      window.onload = function () {
        test("subclass native methods test", function () {
          var mine = new MyArray();

          mine.push(1, 2, 3);
          assert(mine.length == 3, "All the items are on our sub-classed array.");
          assert(!(mine instanceof Array), "We are sub-classing array, though");
        });



        test("subclass native method test2", function () {
          var obj = { a: 1, b: 2, c: 3 };
          assert(obj.keys1().length == 5, "The 3 existing properties plus the new keys method keys1, and keys");
          assert(obj.keys().length == 3, "Only the 3 exiting properties are included.");
          // does not work, cause syntax error
          //        assert(5.add(3) == 8, "Doesnot work, cause syntax error.");
          var n = 5;
          assert(n.add(3) == 8, "It works fine if the number is an varaible.");
          alert((5).add(3) == 8, " Also works if a number is wrapping in parenthesis.");

        }
        );
      }

    </script>

    <style type="text/css" >
      #results li.pass { color: Green }
      #results li.fail { color: Red }
    </style>

</head>
<body>
<ul id="results" />
</body>
</html>
 

 

 

 

 

 

 

分享到:
评论

相关推荐

    Speaking JavaScript

    Objects and Inheritance Chapter 18. Arrays Chapter 19. Regular Expressions Chapter 20. Dates Chapter 21. Math Chapter 22. JSON Chapter 23. Standard Global Variables Chapter 24. Unicode and JavaScript...

    Softgroup Components.NET Subclass and Hook Objects v2.0.3870

    Softgroup .NET Subclass and Hook Objects supply .Net fast, small and lightweight wrapper classes that made easy and secure subclassing and hooking windows for any programmers. Included Classes ...

    This demonstrates hoe to write a subclassing control. And it

    This demonstrates hoe to write a subclassing control. And it has many examples as to how to use the control (included.)

    A freeware MFC class to support MFC subclassing(19KB)

    标题中的"A freeware MFC class to support MFC subclassing"是指一个免费的MFC(Microsoft Foundation Class)类库,它的主要功能是支持MFC的子类化机制。MFC是微软提供的一套C++类库,它封装了Windows API,方便...

    python3.6.5参考手册 chm

    The json module: JavaScript Object Notation The plistlib module: A Property-List Parser ctypes Enhancements Improved SSL Support Deprecations and Removals Build and C API Changes Port-Specific ...

    Subclassing the List View Control using MFC用MFC写的列表视图

    在Windows应用程序开发中,MFC(Microsoft Foundation Classes)是一个强大的库,它提供了对Windows API的封装,使得开发者能够更容易地创建用户界面。本主题聚焦于使用MFC来子类化列表视图控件,这是一种常见的任务...

    Prentice.Hall.C++.GUI.Programming.with.Qt.4.2nd.Edition.2008.chm

    Doing Overlays Using Framebuffer Objects Chapter 21. Creating Plugins Extending Qt with Plugins Making Applications Plugin-Aware Writing Application Plugins Chapter 22. Application Scripting...

    Professional.MFC.with.VC6

    Subclassing MFC Objects About Object-Oriented Design Can You See My House from Here? Summary Chapter 8: Using the Windows Common Controls Overview Common Control Basics Initializing the ...

    subclass-dance-party

    【标题】"subclass-dance-party" 是一个基于JavaScript技术的学生合作项目,旨在探索和实践面向对象编程中的子类化(Subclassing)概念。在这个项目中,开发者可能使用了JavaScript的ES6语法来创建类(Class)并实现...

    子类化实现判断文本框的滑块是否到底

    在编程中,子类化(Subclassing)是一种面向对象编程的概念,它允许我们创建一个新的类(子类)继承自另一个类(父类),并可以扩展或修改父类的行为。在这里,我们将创建一个子类,继承自HTML的`&lt;textarea&gt;`元素或...

    swift demo 包含登陆登出 四个底部TabBar按钮

    Swift是Apple公司推出的一种编程语言,专为iOS、macOS、watchOS和tvOS等平台设计,具有简洁、安全和高性能的特点。在这个“swift demo 包含登陆登出 四个底部TabBar按钮”的项目中,我们可以看到一个典型的iOS应用...

Global site tag (gtag.js) - Google Analytics