JavaScript对象的创建方法及其原型链

对象:属性和方法(供实例使用)

创建JS对象的4种方法

  • 对象字面量
  • 构造函数
  • es6类
  • Object.create()

1、对象字面量:t是Object()对象类型的实例 

const t = {
    name: "molain",
    sayHi: function(){
        console.log("I'm ", name)
    }
}
console.log(t.name) // molain
console.log(t.sayHi()) // I'm  molain

// 原型链
// t.__proto__ === Object.prototype
// Object.prototype.__proto__ === null

// Object.__proto__ === Function.prototype
// Function.__proto__===Function.prototype

2、构造函数:t是test()对象类型的实例

function test() {
    this.name = "molain";
    this.age= function() {
        return 18
    }
}
const t = new test()
console.log(t.name) // molain
console.log(t.age()) // 18

// 构造函数的方法不支持重写,直接是.不出来的
test.prototype.age = function(){
    console.log(1)
} // Uncaught SyntaxError: Identifier 'test' has already been declared at <anonymous>:1:1

// 原型链
// t.__proto__ === test.prototype
// test.prototype.__proto__ === Object.prototype
// Object.prototype.__proto__ === null

// Object.__proto__ === Function.prototype
// Function.__proto__===Function.prototype

3、es6类:t是test()对象类型的实例

class test {
    // 为了初始化数据,非必写
    constructor (name) {
        this.name = name;
        this.age = 18;
    }
    // 所有实例的共同属性可以直接写,不一定非写在构造函数中
    sex = "女"
    sayHi(name){
        console.log("我是", name, this.age, "岁")
    }
}
let t = new test()
console.log(t.name) // undefined
console.log(t.age) // 18
console.log(t.sex) // 女
console.log(t.sayHi()) // 我是undefined 18 岁

// 构造函数的方法支持重写
test.prototype.sayHi= function(){
    console.log(1)
} // 1


// 原型链
// t.__proto__ === test.prototype
// test.prototype.__proto__ === Object.prototype
// Object.prototype.__proto__ === null

// Object.__proto__ === Function.prototype
// Function.__proto__===Function.prototype

4、Object.create():内置对象的标准方法,使用现有的对象字面量作为新对象的原型

const t = {
    name: "molain",
    sayHi: function(){
        console.log("I'm ", name)
    }
}
const test = Object.create(t)
console.log(test.name) // molain
console.log(test.sayHi()) // I'm molain

// 原型链
// test.__proto__ === t
// t.__proto__ === Object.prototype
// Object.prototype.__proto__ === null

// Object.__proto__ === Function.prototype
// Function.__proto__===Function.prototype