是否可以从javascript数组继承和继承?
我想拥有自己的自定义Array对象,它具有Array的所有功能,但包含其他属性.myobj instanceof CustomArray如果实例是我的CustomArray,我将用于执行特定操作.
在尝试子类化并遇到一些问题后,我发现Dean Edwards的这篇文章指出使用Array对象执行此操作无法正常工作.事实证明,Internet Explorer无法正确处理它.但我也发现了其他问题(目前只在Chrome中测试过).
这是一些示例代码:
/**
* Inherit the prototype methods from one constructor into another
* Borrowed from Google Closure Library
*/
function inherits(childCtor, parentCtor) {
function tempCtor() {};
tempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new tempCtor();
childCtor.prototype.constructor = childCtor;
},
// Custom class that extends Array class
function CustomArray() {
Array.apply(this, arguments);
}
inherits(CustomArray,Array);
array = new Array(1,2,3);
custom = new CustomArray(1,2,3);
Run Code Online (Sandbox Code Playgroud)
在Chrome的控制台中输入以下内容即可输出以下内容:
> custom
[]
> array
[1, …Run Code Online (Sandbox Code Playgroud) 即,以下代码如何:
var sup = new Array(5);
sup[0] = 'z3ero';
sup[1] = 'o3ne';
sup[4] = 'f3our';
document.write(sup.length + "<br />");
Run Code Online (Sandbox Code Playgroud)
输出'5'作为长度,当你所做的就是设置各种元素?
我对此代码的"问题"是,我不理解如何在length不调用getLength()或setLength()方法的情况下进行更改.当我执行以下任何操作时:
a.length
a['length']
a.length = 4
a['length'] = 5
Run Code Online (Sandbox Code Playgroud)
在非数组对象上,它的行为类似于dict/associative数组.当我在数组对象上执行此操作时,它具有特殊含义.JavaScript中的哪种机制允许这种情况发生?javascript是否有某种类型的属性系统进行翻译
a.length
a['length']
Run Code Online (Sandbox Code Playgroud)
进入"获取"方法和
a.length = 4
a['length'] = 5
Run Code Online (Sandbox Code Playgroud)
进入"设置"方法?
我正在尝试将元素添加到延迟评估的数组中.这意味着在访问它们之前,不会计算或知道它们的值.这就像我之前提出的问题,但对象是对象.
我最终为对象做的是
Object.prototype.lazy = function(var_name, value_function) {
this.__defineGetter__(var_name, function() {
var saved_value = value_function();
this.__defineGetter__(var_name, function() {
return saved_value;
});
return saved_value;
});
}
lazy('exampleField', function() {
// the code that returns the value I want
});
Run Code Online (Sandbox Code Playgroud)
但我还没有找到一种方法来为真正的数组做这件事.数组没有这样的setter.您可以将函数推送到数组,但是您必须将其作为函数调用它来返回您真正想要的对象.我现在正在做的是创建了一个我将其视为数组的对象.
Object.prototype.lazy_push = function(value_function) {
if(!this.length)
this.length = 0;
this.lazy(this.length++, value_function);
}
Run Code Online (Sandbox Code Playgroud)
所以我想知道的是,还有一种方法可以在数组上执行此操作而不是假数组吗?
更新:以下函数仅在value_function返回基本数据类型时有效.
Array.prototype.lazy_push = function(value_function) {
var a = this,
i = this.length;
this.push({
toString: function() {
return a[i] = value_function();
}
});
}
Run Code Online (Sandbox Code Playgroud)
如果您尝试推送一个包含属性的对象,则在直接访问该对象之前,您将无法访问这些属性.这不会发生在setter中,这就是为什么我想要一些Javascript的设置语法.现在我将使用假阵列,这对我正在做的事情已经足够了.
有没有办法复制全局对象(Array,String ...),然后扩展副本的原型而不影响原始对象?我试过这个:
var copy=Array;
copy.prototype.test=2;
Run Code Online (Sandbox Code Playgroud)
但是如果我检查Array.prototype.test它是2,因为Array对象是通过引用传递的.我想知道是否有办法使"复制"变量表现得像一个数组但可以扩展而不会影响原始的Array对象.