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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值