JavaScript继承和Array对象(需要解释才能理解)

时间:2015-04-30 11:42:19

标签: javascript arrays inheritance

我一直在尝试了解Javascript中的继承,到目前为止,我已经阅读了很多关于此的网站(包括javascript.info和Crockford的Javascript好部分) - 但我可以'似乎理解像Array继承这样简单的东西。

也许如果我举一个例子,有人可以纠正我,并告诉我我的错误。

function ExtendedArray() {
    Array.call(this, arguments);

    this.test = function () {
        return 'something';
    }
}

//I think this is the most standard way to extend a class?
ExtendedArray.prototype = [];
ExtendedArray.prototype.constructor = ExtendedArray;

$scope = {};

$scope.arr = new Array(1, 2, 3);
$scope.concatArr = [].concat($scope.arr);

$scope.x = new ExtendedArray(1, 2, 3);    //empty | instanceof Array = true
$scope.concatX = [].concat($scope.x);     //empty

$scope.y = new ExtendedArray();          //instanceof Array = true
$scope.y.push(1, 2, 3);                  //works - elements are added!
$scope.concatY = [].concat($scope.y);    //concats it like a object

这是一个JS-Fiddle:

http://jsfiddle.net/superasn/pq2j139c/

有些问题:

  1. 如何修复此代码以使ExtendedArray表现为数组?
  2. 如您所见,$scope.x为空。为什么构造函数不起作用?
  3. push功能有效!?但是concat失败了吗?如何让concat工作?
  4. 我看到有一些库可以扩展Classes,这是一种更好的JS继承方法吗?
  5. 您的建议表示赞赏!

1 个答案:

答案 0 :(得分:0)

您只需在构造函数中调用[].push.apply(this, arguments);

angular.module('myApp', [])
.controller('mainCtrl', ['$scope', function($scope) {

    var __extends = this.__extends || function (d, b) {
                for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
                function __() { this.constructor = d; }
                __.prototype = b.prototype;
                d.prototype = new __();
            };
    
    function ExtendedArray() {
        Array.call(this, arguments);
        
        [].push.apply(this, arguments);
        
        this.test = function () {
            return 'something';
        }
    }
    
    __extends(ExtendedArray, Array);

    $scope.arr = new Array(1, 2, 3);
    $scope.concatArr = [].concat($scope.arr);
    
    $scope.x = new ExtendedArray(1, 2, 3);    
    $scope.concatX = [].concat($scope.x);
    
    $scope.y = new ExtendedArray();    
    $scope.y.push(1, 2, 3);
    $scope.concatY = [].concat($scope.y);
    
    $scope.isArray = function(v) {
        return v instanceof Array;
    }
    
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="mainCtrl">
   <div class="content">
       Arr: Val = {{arr}} / Concat = {{concatArr}} / Is Array? {{isArray(arr)}}
       
       <hr/>

       X: Val = {{x}} / Concat = {{concatX}} / Is Array? {{isArray(x)}}

       <hr/>

       Y: Val = {{y}} / Concat = {{concatY}} / Is Array? {{isArray(y)}}
       
    </div>
</div>