我一直在尝试了解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/
有些问题:
ExtendedArray
表现为数组?$scope.x
为空。为什么构造函数不起作用?push
功能有效!?但是concat
失败了吗?如何让concat
工作?您的建议表示赞赏!
答案 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>