/*
在ES6中判断变量是否为数组
鉴于数组的常用性,在ES6中新增了Array.isArray方法,使用此方法判断变量是否为数组,则非常简单
*/
/*
一 prototype介绍
prototype对象是实现面向对象的一个重要机制。每个函数也是一个对象,它们对应的类就是function,
每个函数对象都具有一个子对象prototype。Prototype 表示了该函数的原型,prototype表示了一个类的属性的集合。
当通过new来生成一个类的对象时,prototype对象的属性就会成为实例化对象的属性。
下面以一个例子来介绍prototype的应用,代码如下:
<script language="javascript">
//定义一个空类
function HelloClass(){
}
//对类的prototype对象进行修改,增加方法method
HelloClass.prototype.method=function(){
alert("prototype测试");
}
var obj=new HelloClass(); //创建类HelloClass的实例
obj.method();
//调用obj的<a href="https://www.baidu.com/s?wd=method%E6%96%B9%E6%B3%95&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjms" target="_blank" class="baidu-highlight">method方法</a>
</script>
当用new创建一个对象时,prototype对象的属性将自动赋给所创建的对象,例如:
<script language="javascript">
//定义一个只有一个属性的类
function HelloClass(){
this.name="javakc";
}
//使用函数的prototype属性给类定义新属性
HelloClass.prototype.showName=function(){
alert(this.name);
}
var obj=new HelloClass(); //创建类HelloClass的一个实例
//调用通过prototype原型对象定义的showName方法
obj.showName();
</script>
二 利用prototype实现继承
<script language="javascript">
function HelloClass(){
//构造方法
}
function HelloSubClass(){
//构造方法
}
HelloSubClass.prototype=HelloClass.prototype;
HelloSubClass.prototype.Propertys="name";
HelloSubClass.prototype.subMethods=function(){
//方法实现代码
alert("in Methods");
}
var obj=new HelloSubClass();
obj.subMethods();
</script>
在以上的代码中,首先是HelloSubClass具有了和HelloClass一样的prototype,
如果不考虑构造方法,则两个类是等价的。随后,又通过prototype给HelloSubClass赋予了额外的属性和方法,
所以HelloSubClass是在HelloClass的基础上增加了新的属性和方法,从而实现了类的继承。
*/
if (!Array.isArray) {
Array.isArray = function (arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
/*
返回符合测试条件的第一个数组元素值,如果没有符合条件的则返回 undefined。
*/
/*
这个扩展,理论上应该判断下callback是否是function
if(typeof callback !== 'function') {
throw new TypeError('callback should be a function');
}
*/
if (!Array.prototype.find) {
Array.prototype.find = function (callback) {
var length = this.length;
for (var i = 0; i < length; i++) {
var element = this[i];
/* //遍历数组,依次执行回调函数,一旦回调函数返回值为真,
返回此项元素,否则继续执行 */
if (callback.call(this, element, i, this)) {
return element;
}
}
return undefined;
};
}
/*
includes()方法用来判断一个数组是否包含一个指定的值,如果是返回 true,否则false
*/
// for ie 11
if (!Array.prototype.includes) {
Array.prototype.includes = function (value) {
/* 查找value 的位置,位置不为-1 则表示存在 */
return this.indexOf(value) !== -1;
};
}