美文网首页前端学习笔记
简单类型与对象(复杂类型)的区别

简单类型与对象(复杂类型)的区别

作者: _ClariS_ | 来源:发表于2019-07-26 18:59 被阅读5次

全局对象

ECMAScript 规定全局对象叫做 global,但是浏览器把 window 作为全局对象(浏览器先存在的)
window 就是一个哈希表,有很多属性。
window 的属性就是全局变量。
这些全局变量分为两种:

  1. 一种是 ECMAScript 规定的:
  • global.parseInt
  • global.parseFloat
  • global.Number
  • global.String
  • global.Boolean
  • global.Object
  1. 一种是私有的(浏览器自己加的属性):
  • window.alert(弹框提示)
  • window.prompt(用户填写)
  • window.comfirm(确认)
  • window.console.log
  • window.console.dir
  • window.document(文档 DOM)
  • window.document.createElement
  • window.document.getElementById
  • window.history(浏览器 BOM)

window 可省略不写

全局函数

  1. Number
    两种用法:
    Number(1)基本类型(非对象)
    var n = new Number(1) 创建一个 Number 对象

那么 1 与 new Number(1) 有什么区别呢?

1 与 new Number(1) 的区别 1 与 new Number(1) 的区别

var n1 = 1这种写法的缺点:基本类型(简单类型)是没有属性的(toString、valueOf、toFixed等),但我们依然可以做到
n1.toString() // "1"
n1.valueOf() // 1
n1.toFixed(2) // "1.00"
为什么上面声明的一个简单的 1 也有属性呢?因为这里采用的是一种临时转换的方法,举例说明:
n1.toString() 首先声明一个临时的对象 temp ,令 temp = new Number(n1),然后通过调用 temp 里的函数 temp.toString() 将数字 1 变为字符串 '1',把字符串 '1' 作为n1.toString() 的最终结果,然后会消去 temp,最终得到n1.toString() // "1"

临时转换 temp
  1. String
    有两种方法声明一个字符串:
    var s1 = 'hello' 基本类型(非对象)
    var s2 = new String('hello') 创建一个 String 对象

'hello' 与 new String('hello') 的区别是什么?
var s1 = 'hello'声明的是一个基本类型,直接存放在 Stack 中,而 var s2 = new String('hello') 声明的是一个对象,对象存放在 Heap 中,对象的地址存放在 Stack中。

'hello' 与 new String('hello') 的区别

String 的部分 API

部分 string methods

更多Useful string methods

  1. Boolean
    var b = new Boolean(true) 创建一个 Boolean 对象
    true 与 new Boolean(true) 的区别是什么?
true 与 new Boolean(true) 的区别

一个题目:

var f1 = false
var f2 = new Boolean(false)
问:
if(f1){console.log(1)}
if(f2){console.log(2)}
打印出的结果是 1 还是 2 ?

答案:

  1. Object
    var o1 = {}
    var o2 = new Object()
    o1 和 o2 没区别,但 o1 与 o2 并不相等

总结:

简单类型与复杂类型的区别
  • 基本类型(number、string、boolean)不加 new 返回的值依旧是一个基本类型,加 new 则返回的值变为一个对象
  • 复杂类型(对象)不管加不加 new 返回的值都一样,都为对象

相关文章

网友评论

    本文标题:简单类型与对象(复杂类型)的区别

    本文链接:https://www.haomeiwen.com/subject/ctyhrctx.html