每周前端知识整理(15.07.12)

来源:互联网 发布:java file.length单位 编辑:程序博客网 时间:2024/05/21 10:12

1.关于NaN

NaN的定义和isNaN()的用法不用说了。这周看到一个写法可以判断一个变量是否为NaN

if (a!=a) 

虽然isNaN()也可以判断,但是上边的方法可以判断是否“只”为NaN,而isNaN()如果是字符串等情况返回的也是true。

2. hasOwnProperty , in , isPrototypeOf

三个功能相近的方法,之前没有细看,总结一下。先上MDN的解释

hasOwnProperty: 

obj.hasOwnProperty(pro)

Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.

in: 

prop in objectName

The in operator returns true if the specified property is in the specified object.

isPrototypeOf:

prototypeObj.isPrototypeOf(obj)

The isPrototypeOf method allows you to check whether or not an object exists within another object's prototype chain.

解释上说的很清楚,hasOwnProperty是对象用来判断一个对象是否“直接”包含某个属性,也就是说,它不能检索到对象原型链中的属性。所以说任何通过obj.prototype定义的属性,继承的属性,自带属性(例如字符串的length)等,返回的都是false。obj可以重新定义hasOwnProperty这个方法,比如让他持续return false。

对于 in ,检索的范围要比hasOwnProperty大一些,可以检索到原型链中去。换句话说,基本上obj.之后能“点”出来的东西,都是能通过in 返回true的。为什么说基本上而不是所有呢,因为有个反例,代码如下:

var a = "abc";var b = new String('abc');'length' in a //error'length' in b //true
这个具体原因我会接着研究一下,写到以后的总结中。

此外,hasOwnProperty 和 in 方法还可以判断Array,毕竟 typeof [] 也是 object。。。(这么说null也成了?)

在对Array进行判断的时候,主要以数组序号作为参数,如下:

var a = new Array[1,2,3];var b = [1,2,3];a.hasOwnProperty(0); /true0 in a; //true b.hasOwnProperty(0); //true0 in b; //true3 in b; //false
可以看出来,如果序号是超过数组长度了,则返回false,其实目前还没有想到这个有什么用途。。
最后说一下isPrototypeOf,他的作用是检查一个obj是否在另一个的原型链中。这个感觉用的比较少

0 0
原创粉丝点击