来自面向对象的 JavaScript 书的问题:想象 Array() 不存在,并且数组文字符号也不存在。创建一个名为 MyArray() 的构造函数,其行为尽可能接近 Array()。
我认为测试我的技能将是一个很好的挑战。这是我想出的,但它不起作用并且非常不完整..我有点难过:
function MyArray(){
// PRIVATE FIELDS -----------------------
var initialData = arguments;
var storage;
// PRIVATE METHODS ----------------------
function refresh(){ //this doesn't work :(
for(var i = 0; i < storage.length; i++){
this[i] = storage[i]
}
};
function initialize(){
storage = initialData;
refresh();
}
function count(){
var result = 0;
for(var item in this){
//console.log(item, parseInt(item), typeof item);
if(typeof item == 'number'){
result++;
}
}
return result;
};
initialize();
// PUBLIC FIELDS -------------------------
this.length = count();
// PUBLIC METHODS ------------------------
//todo:
this.push = function(item){
refresh();
}
this.pop = function(){}
this.join = function(){}
this.toString = function(){}
}
var c = new MyArray(32,132,11);
console.log(c, c.length);
这不适用于任何生产代码或任何项目.. 只是为了尝试更多地学习 JavaScript。任何人都可以尝试帮助我使用此代码吗?