前端基础知识总结---JS高级篇(3)_对象高级

本文详细探讨了JavaScript中对象的五种创建模式(构造函数、对象字面量、工厂函数、自定义构造函数及原型组合)以及三种继承方式(原型链、借用构造函数和组合继承)。讲解了每种模式的工作原理和应用场景,并揭示了函数和对象的创建奥秘。
摘要由CSDN通过智能技术生成

1. 对象的创建模式

1). Object构造函数模式

var obj = new Object()
obj.name = 'Tom'
obj.setName = function(name){this.name=name}

2). 对象字面量模式

var obj = {
	name : 'Tom',
	setName : function(name){this.name = name}
}

3). 工厂函数模式

// 工厂函数: 返回一个需要的数据的函数
  function Person(name, age) {
    return {
      name: name,
      age: age
    }
  }
  var person1 = Person('kobe', 43);

4). 自定义构造函数模式

function Person(name, age) {
	this.name = name
	this.age = age
	this.setName = function(name){this.name=name}
}
var person1 = new Person('tom', 12)

5). 构造函数+原型的组合模式

function Person(name, age) {
	this.name = name
	this.age = age
}
Person.prototype.setName = function(name){this.name=name}
var person1 = new Person('tom', 12)

2. 继承模式

1). 原型链继承 : 得到方法

  function Person(name, age) {  
    this.name = name;
    this.age = age;
  }
  Person.prototype.showName = function () {
    console.log(this.name);
  }

  // 原型继承: 子类的原型 成为 父类的实例
  // Child.prototype = {constructor: Child}
  Child.prototype = new Person();
  Child.prototype.constructor = Child;     // 要手动加上原型的constructor属性
  // 定义一个child类
  function Child(name, age) {
    this.name = name;
    this.age = age;
  }
  
  var child1 = new Child('xiaoming', 18);

2). 借用构造函数继承 : 得到属性

function Parent(xxx){this.xxx = xxx}
Parent.prototype.test = function(){}
function Child(xxx,yyy){
  Parent.call(this, xxx) //借用父类型的构造函数 
}
var child = new Child('a', 'b')  //child.xxx为'a', 但child没有test()

3). 组合继承

function Parent(xxx){this.xxx = xxx}
Parent.prototype.test = function(){}
function Child(xxx,yyy){
  Parent.call(this, xxx) //借用构造函数   this.Parent(xxx)
}
Child.prototype = new Parent() //得到test()
Child.proptotype.constructor = Child
var child = new Child() //child.xxx为'a', 也有test()

3. 理解

1). 定义一个函数背后做了什么?

创建一个Function的实例对象
给对象添加prototype属性, 其值为object空对象(原型对象)
给原型对象添加constructor属性, 指向当前函数对象

2). new一个对象背后做了些什么?

创建一个新的空对象
给对象设置__proto__, 值为构造函数对象的prototype属性值
通过对象执行构造函数体(给对象添加属性/方法)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智者_若愚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值