gpt4 book ai didi

Javascript继承自数组并使其成为全局的

转载 作者:行者123 更新时间:2023-11-30 13:29:34 29 4
gpt4 key购买 nike

下面的小演示说明了我的问题:

// 1 - Define a global reference to classA
(function() {
window.classA = new ClassA();
})();

// 2 - ClassA object definition
function ClassA() {
this.test1 = function() {
document.write('test1');
};
}

// 3 - ClassA inherits Array and has a test function
ClassA.prototype = new Array;
ClassA.prototype.test2 = function() {
document.write(this[0]);
}

// 4 - Test our ClassA
var c = new ClassA();
c.test1();
c.push('test2');
c.test2();

// 5 - Test our global ClassA
classA.test1();
classA.push('test2'); // doesn't work
classA.test2(); // doesn't work

在这里试试:http://jsfiddle.net/SPSW4/

定义全局变量 classA(ClassA 实例)的正确方法是什么?

最佳答案

正确的方法是在立即调用的函数表达式中创建伪子类 Array 构造函数,然后将结果公开给显式全局对象。

(function( global ) {
// Declare the ArrayLike constructor
function ArrayLike() {
var args = [].slice.call( arguments ),
length = args.length, i = 0;

this.length = length;

for ( ; i < length; i++ ) {
this[ i ] = args[ i ];
}
return this;
}
// Define ArrayLike's prototype by creating a new Array instance
ArrayLike.prototype = new Array();

// Define your own proto method
ArrayLike.prototype.firstChar = function() {
var ret = [],
length = this.length, i = 0;

for ( ; i < length; i++ ) {
ret[ i ] = this[ i ][ 0 ];
}
return ret;
};
// Expose the ArrayLike constructor.
global.ArrayLike = ArrayLike;
})( this );

var a = new ArrayLike( "alpha", "beta", "gamma" );

console.log( a.push("delta") ) // 4
console.log( a ); // ["alpha", "beta", "gamma", "delta"]
console.log( a.firstChar() ); // ["a", "b", "g", "d"]

现场观看:http://jsfiddle.net/rwaldron/gLdkb/

关于Javascript继承自数组并使其成为全局的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7293738/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com