首页 > Web开发 > 详细

javascript那些不应该忽视的细节

时间:2014-02-15 04:52:08      阅读:363      评论:0      收藏:0      [点我收藏+]

1.null与Object.prototype使用typeof操作符结果都是object,但他们都不是Object的实例。

typeof null  // object
null instanceof Object  // false

typeof Object.prototype // object
Object.prototype instanceof Object // false

理解:typeof是判断数据所属的类型,而instanceof判断一个对象是不是另一个‘类’的实例。(这是一句废话)所有的对象使用typeof运算返回object都不算错,我们可以认为一切皆是Object。但是,这没有什么意义;a instanceof C表示a是否是由C创造出来。显然Object是不能new一个null出来的。虽然Object.prototype是一个真正的object,但是,它也不是Object构造出来的。想想看,哪个构造器能构造自己的原型,而且原型是自函数产生那一刻便存在的。

2.在js中有些符号没有传递性以及数学上的可推导性。例如a<b,b<c;那么a<c。在js中未必成立

 true < ‘2‘ // true
 ‘2‘ < ‘a‘ // true
true < ‘a‘ // false.不管怎么样都是false

结论:布尔值可以与数字(无论是Number还是String)比较大小,true为1,false为0;当至少有一边是非数字字符串时,如:‘a‘,‘sed‘,‘2ws‘......,另一边必须也是字符串,可以是数字的。如:‘2‘,‘b‘等。在与字符串做加法运算时,true能直接转换成‘true‘.

3.null与0的激情。直接看代码

null<0 //false
null == 0 // false
null > 0 // false

null >=0 // true
null <=0 // true

文档:ECMASCRIPT-262有关<=或者>=规则最后一条是这样的:If r is true or undefined, return false. Otherwise, return true.而刚好r是false,结果就返回true了。但是>或者<而是这样的:If r is undefined, return false. Otherwise, return r.这不是null与0的激情,应该是>=与<=的乱伦。(我猜测是走到最后,由这条规则引起的。文档实在是羞涩)

4.不明白

bubuko.com,布布扣
function A(){}

var a = new A();

var b = A.prototype;

A.prototype = {}; // 为啥这句对下面结果有影响
    
console.log(a instanceof b.constructor);
bubuko.com,布布扣

已经明白。保存之前的原型,只是绕了一圈。b.construtor还是A。

5.instanceof的结果跟原型有关

bubuko.com,布布扣
function A(){}
function B(){}

var ax = new A();

A.prototype = B.prototype = {};

var ay = new A(), b = new B();

ax instanceof A // false

ay instanceof A // true

b instanceof B // true 的确是B
bubuko.com,布布扣

6.最后贴几道题

bubuko.com,布布扣
//1
var a = "123abc";
alert(a);
a.toString = function(){
     return 1;   
}
alert(a);


//2
alert(typeof Function.prototype);
alert(Object.prototype instanceof Function);
alert(Function.prototype instanceof Function);

//3
null == undefined
null >= undefined
null <= undefined

//4
function A(){
    return {
        toString:function(){return 2}
    };   
}
A.prototype.toString = function(){ return 3}

var a = new A();
alert(a)
bubuko.com,布布扣

javascript那些不应该忽视的细节

原文:http://www.cnblogs.com/m-v-p/p/3549528.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!