javascript那些不该该忽视的细节

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

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构造出来的。想一想看,哪一个构造器能构造本身的原型,并且原型是自函数产生那一刻便存在的。es6

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'.lua

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

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的激情,应该是>=与<=的乱伦。(我猜想是走到最后,由这条规则引发的。文档实在是羞涩)prototype

4.不明白code

function A(){}

var a = new A();

var b = A.prototype;

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

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

5.instanceof的结果跟原型有关对象

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

6.最后贴几道题blog

//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)
相关文章
相关标签/搜索