当输入 JavaScript 控制台时,jQuery 对象显示为数组。然而,它仍然是 jQuery 对象的一个实例。
var j = jQuery();
=> []
console.log(j);
=> []
console.log('test with string concat: ' + j);
=> test with string concat: [object Object]
j instanceof Array
=> false
j instanceof jQuery
=> true
如何用自己的对象复制这一点?
- - - - - 编辑 - - - - -
感谢 ZER0 解决了这个问题。下面是一些示例代码,用于创建一个像控制台中的 jQuery 一样工作的对象:
var Foo = function() {
this.splice = Array.prototype.splice;
Array.prototype.push.apply(this, arguments);
return this;
}
var f = new Foo();
=> []
console.log(f);
=> []
console.log('test with string concat: ' + f);
=> test with string concat: [object Object]
f instanceof Array
=> false
f instanceof Foo
=> true
很酷。
我相信他们有类似的东西:
// Adding items to an object like an Array:
var myObject = {splice : Array.prototype.splice};
Array.prototype.push.call(myObject, 1, 10, "foo");
// Getting items from an object like an Array:
alert(Array.prototype.slice.call(myObject, 0));
console.log(myObject);
alert(myObject);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)