感谢Bosn的分享闭包
玩转数据类型app
《JS公开课》系列分享
1). 认识JavaScript DONE
2).数据类型 & 操做符
3). 谈对象
4). 基于原型的继承机制
5). 运行上下文
6). 神奇的闭包
7). 高性能JavaScript性能
首先作一个回顾spa
5 – “4” 5 + “4” +!{}[true] +[1] +[1, 2] 7 – “a” 7 / 0 5 + “4” 5 + null 4 == “4.00” 4 === “4.00” null == undefined 0 == false 0 == null null == false
首先各位作一下上面的题目吧,看看本身作出来的和结果是否是同样。code
作完题目了,先别急,不懂的咱们会在下文讲到,懂的就当补脑了,也能够复习一下。orm
你们众所周知,JS分为以上两种类型,一种是对象,另一种是基元类型。对象
var x = ‘The answer is ‘ + 42; var y = 42 + ‘ is the answer’; “37” – 7 //30 “37” + 7 //'377'
最经常使用且容易疑惑的是加法运算,除了算数意义,还表示着字符串拼接。blog
上面的代码就能够明显看出来,继承
细心看下这一段ECMA的标准ip
二元加法操做符“+”:任意一个操做数是字符串,理解为字符串拼接。
二元减法操做符“-”:操做数尝试转换成数字并作减法运算。
11.9.3 The Abstract Equality Comparison Algorithm The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows: 1. If Type(x) is the same as Type(y), then a. If Type(x) is Undefined, return true. b. If Type(x) is Null, return true. c. If Type(x) is Number, then i. If x is NaN, return false. © Ecma International 2011 81 ii. If y is NaN, return false. iii. If x is the same Number value as y, return true. iv. If x is +0 and y is -0, return true. v. If x is -0 and y is +0, return true. vi. Return false. d. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions). Otherwise, return false. e. If Type(x) is Boolean, return true if x and y are both true or both false. Otherwise, return false. f. Return true if x and y refer to the same object. Otherwise, return false. 2. If x is null and y is undefined, return true. 3. If x is undefined and y is null, return true. 4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y). 5. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y. 6. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y. 7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y). 8. If Type(x) is either String or Number and Type(y) is Object, return the result of the comparison x == ToPrimitive(y). 9. If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) == y. 10. Return false.
再列一段,ECMA标准规范上面写明了,==进行比较的时候采起怎么处理的方式。
今天晚上先弄到这里,明天继续。把没写完的搞完,包括包装对象Wrapper Object
var a = “string”; alert(a.length); //6 a.t = 3; alert(a.t); //undefined
定义的a是一个字符串,自己是没有length这个方法的,为何弹出的会是6呢?难道转换成了Object?
可是后面的alert弹出的倒是undefined,证实了a添加t方法失败,那就是说a不是一个Object。为何会出现这个区别呢?先看下图
实际上,在JS处理这个问题的时候有本身的处理方式。
var a = “string”; alert(a.length);//当处理这个a.length的时候,实际上通过了如下步骤 //这个tmp是虚构的,方便你们理解 //var tmp = new String(a); //tmp.length;//6 //a.length其实是tmp.length //tmp是一个String对象有length这个方法 //而后处理完了以后tmp就被销毁了 //因此a仍是一个String
苦B的在公司加班中。。。下一条,其实也是一个思想。
a.t = 3; alert(a.t); //这里的处理方式跟上面的实际上是同样的 //var tmp = new Object(a); //tmp.t = 3;实际上添加了t这个方法,可是处理完这一条以后,被销毁。 //因此alert(a.t)这个时候的a仍是一个字符串。没有t方法。