在JavaScript中,数组可以使用Array构造函数来创建,或使用[]快速创建,这也是首选的方法。数组是继承自Object的原型,并且他对typeof没有特殊的返回值,他只返回'object'。
js中,可以说万物皆对象(object),一个数组也是一个对象(array)。
很多对象都有很多很方便的方法 比如数组的push,concat,slice等等,但是如果一些对象,它没有实现这些方法,我们还是想使用这些功能。那该怎么办呢?
1、很多方法都提供了非常高效的实现, 我们可以仿照它们的实现。
比如IE8以下的浏览器不支持Array的indexOf方法,为了让数组支持indexOf,我们可以自己写一个方法,实现indexOf方法:
(用IE浏览器调试 按F12,可以选择浏览器版本到IE5。)
var arr = [, , , ]; if (Array.prototype.indexOf) { alert("你的浏览器支持indexOf方法。"); } else { alert("你的浏览器不支持indexOf方法。"); } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(item) { for (var i = ; i < this.length; i++) { if(this[i]==item){ return i; } } return -; } } alert(arr.indexOf()); alert(arr.indexOf());
当然这个方法是很垃圾的。在这里具体的实现 我就不献丑了,提供一个百度上copy的版本:
有兴趣的话可以看看v8引擎是怎么实现的:https://github.com/v8/v8/blob/master/src/js/array.js
if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length >>> ; var from = Number(arguments[]) || ; from = (from < ) ? Math.ceil(from) : Math.floor(from); if (from < ) from += len; for (; from < len; from++) { if (from in this && this[from] === elt) return from; } return -; }; }
2、继承——call和apply方法
如果我们每有一个对象,那每个对象就要自己写一遍实现是不是很麻烦?
在高级语言中,我们可以用继承来解决问题,比如下面的java代码:
public class MyList<E> extends ArrayList<E> { public void myAdd(E e){ super.add(e); System.out.println("Add:"+e); } }
但是js中没有继承的概念啊,我们可以用call和apply来解决这样的问题。
上面的代码就可以改写为:
var myObject = function(){ } myObject.prototype.add = function(){ Array.prototype.push.call(this,arguments); //输出arguments for(var i=;i<arguments.length;i++){ console.log("Add:"+arguments[i]); } } var obj = new myObject(); obj.add(,,);
这里可以看到:虽然用高级语言的继承方式实现了myAdd方法,但是现在myAdd方法只能传一个参数,如果要传多个参数,则需要再写一个public void myAdd(E[] e)方法,甚至是public void myAdd(List
(ps,其实在java中可以写public void myAdd(E... e),这个是不定参数,用法上public void myAdd(E[] e)是一样的)
call和apply方法用于改变函数内this指针的指向,call只有两个参数,而apply通常是知道参数个数之后才使用的,下面以例子说明:
var Obj = function(name){ this.name = name; } Obj.prototype.getName = function(){ return this.name; } var obj1 =new Obj("zou"); var obj2 = {name:'andy'}; var name = obj1.getName.call(obj2); alert(name);
参考是:
apply(object,arg1,arg2,....)
call(object,[arg1,arg2,....])
call后面只能跟一个“数组”,包括了所有的参数。而apply则是一颗语法糖,如果知道参数的个数,用apply将很方便。
上面的object也可以是null或者undefined,这样,这个object就是global object(window),例如,还是接着上例:
var name = 'goo'; alert(obj1.getName.call(null)); (在严格模式下,由于全局对象是null,故会抛出异常:Uncaught TypeError: Cannot read property 'name' of null)
3、Object.defineProperty
(注意:不要在IE8以下使用该类特性)
微软:将属性添加到对象,或修改现有属性的特性。
getter、setter,
其实js中对于对象的属性也有getter和setter函数,不过个人觉得js中的getter和setter更像C#一些。
例如下面的代码就定义了一个getter/setter:
function myobj(){ } Object.defineProperty(myobj.prototype,'length',{ get:function(){ return this.length_; //这里不能是length。 }, set:function(value){ return this.length_=value; } });
注释的地方不能是length,否则会无限递归。
也可以去掉set,让length变量只读。
Object.defineProperty(myobj.prototype,'length',{ get:function(){ return this.length_; //这里不能是length。 }, /*set:function(value){ return this.length_=value; }*/ }); myobj.length = 3;
这个代码会抛出异常:Uncaught TypeError: Cannot set property length of #
要让对象的属性只读,还可以用writable:false,
Object.defineProperty(myobj.prototype,'length',{ writable:false });
writable:false不能与get set共存,否则会抛出Type Error。
configurable:是否能用delete语句删除,但是configurable属性好像在严格模式下才有效,这样的代码在非严格模式下仍然能执行:(严格模式报错)
Object.defineProperty(myobj.prototype,'length',{ configurable:false }); var obj = new myobj(); delete obj.length;
value:指定该对象的固定值。value:10,表示这个对象初始值为10.
在非严格模式下,这样的代码不会报错,严格模式下会报错:
Object.defineProperty(myobj.prototype,'length',{ writable:false, value:'10' }); var obj = new myobj(); obj.length = 100;
可以用getOwnPropertyDescriptor来获取并修改这些值,比如说,现在我的length属性是只读的。
运行这样的代码,结果却报错了:
Object.defineProperty(myobj.prototype,'length',{ value:, writable:false, }); var descriptor = Object.getOwnPropertyDescriptor(myobj.prototype, "length"); descriptor.writable = true; Object.defineProperty(myobj.prototype,'length',descriptor); Uncaught TypeError: Cannot redefine property: length
这是因为configurable的默认值是false,在调用了defineProperty之后,configurable就具有false属性,这样就不能逆转了。以后就不能改了。
所以必须使用 configurable:true,这个对象属性才是可以修改的,完整的代码如下:
Object.defineProperty(myobj.prototype,'length',{ value:, writable:false, configurable:true }); var descriptor = Object.getOwnPropertyDescriptor(myobj.prototype, "length"); descriptor.writable = true; Object.defineProperty(myobj.prototype,'length',descriptor); myobj.prototype.length = ; var obj = new myobj(); alert(obj.length);
可以加上一句descriptor.configurable = false;
表示这个属性我修改了,以后你们都不能再修改了
这个特性在很多时候也有用,数组Array的push pop等方法,如果使用call、apply,要求对象的length可变。如果对象的length属性只读,那么调用call、apply时,会抛出异常。
就比如DOMTokenList对象,它的length就是不可以变的。我拿到了一个DOM对象DOMTokenList,
但是它的configurable是true,我们可以修改让它的length属性可以变啊:
看见没,这个configurable是true,而setter是undefined,我们给它写一个set方法,不就可以了吗?
var descriptor = Object.getOwnPropertyDescriptor(DOMTokenList.prototype,'length'); descriptor.set = function(value){ this.length = value; } Object.defineProperty(DOMTokenList.prototype,'length',descriptor);
然后运行,
又抛出了一个异常,Uncaught RangeError: Maximum call stack size exceeded(…)
这是因为,我们在set this.length时,它会在我们写的那个set方法中无限递归。
因此,我们需要使用delete消除length属性的影响,也就是:
var descriptor = Object.getOwnPropertyDescriptor(DOMTokenList.prototype,'length'); descriptor.set = function(value){ delete DOMTokenList.prototype.length; this.length = value; } Object.defineProperty(DOMTokenList.prototype,'length',descriptor);
这样,DOMTokenList也就支持了push,pop等等操作了。
Array.prototype.push.call(document.body.classList,'abc')
然后再行封装
DOMTokenList.prototype.push = function(){ Array.prototype.push.call(document.body.classList,Array.prototype.slice.call(arguments)); }
Array.prototype.slice.call(arguments)方法用于把arguments对象转换为数组。

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
