JavaScript创建对象的一系列方式及全局对象window

92 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第11天,点击查看活动详情

创建对象的三种方式

无脑创建

// 一系列的学生对象
var stu1 = {
  name: "bajie",
  age: 18,
  height: 1.88,
  running: function() {
    console.log("running~")
  }
}
var stu2 = {
  name: "kobe",
  age: 30,
  height: 1.98,
  running: function() {
    console.log("running~")
  }
}
var stu3 = {
  name: "james",
  age: 25,
  height: 2.05,
  running: function() {
    console.log("running~")
  }
}

工厂函数

// 工厂函数(工厂生产student对象) -> 一种设计模式
// 通过工厂设计模式, 自己来定义了一个这样的函数
function createStudent(name, age, height) {
  var stu = {}
  stu.name = name
  stu.age = age
  stu.height = height
  stu.running = function() {
    console.log("running~")
  }
  return stu
}
var stu1 = createStudent("bajie", 18, 1.88)
var stu2 = createStudent("kobe", 30, 1.98)
var stu3 = createStudent("james", 25, 2.05)
console.log(stu1)
console.log(stu2)
console.log(stu3)

构造函数 + new 关键字

// JavaScript已经默认提供给了我们可以更加符合JavaScript思维方式(面向对象的思维方式)的一种创建对象的规则
// 在函数中的this一般指向某一个对象
/*
  如果一个函数被new操作符调用
    1.创建出来一个新的空对象
    2.让this指向这个空对象
    3.执行函数体的代码块
    4.如果没有明确的返回一个非空对象, 那么this指向的对象会自动返回
*/
function Coder(name, age, height) {
  this.name = name
  this.age = age
  this.height = height
  // 构造函数中的方法称为类方法
  this.running = function() {
    console.log("running~")
  }
}
// 在函数调用的前面加 new 关键字(操作符)
var stu1 = new Coder("bajie", 18, 1.88)
var stu2 = new Coder("kobe", 30, 1.98)
console.log(stu1, stu2)
  • 注意点:构造函数的名称使用大驼峰,普通函数使用小驼峰
  • 函数本身也是对象

全局对象 window

// 浏览器中存在一个全局对象object -> window
// 作用一: 查找变量时, 最终会找到window头上
// 作用二: 将一些浏览器全局提供给我们的变量/函数/对象, 放在window对象上面
// 作用三(了解): 使用var定义的变量会被默认添加到window上面(除了函数里的用var定义的)
console.log(window)

// 使用var定义变量
var message = "Hello World"

function foo() {
  // 自己的作用域
  // abc()
  // alert("Hello World")
  console.log(window.console === console)

  // 创建一个对象
  // var obj = new Object()
  console.log(window.Object === Object)

  // DOM
  console.log(document)

  // window.message
  console.log(window.message)
}
foo()