• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

黄文超

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

js中创建对象的方法

js中对象创建模式

一、普通方式

1、使用Object空对象创建对象

var p = new Object()
p.age = 12
p.name = 'hc'
p.setAge = function(age) {
    this.age = age
}
问题:
	1、代码太多

2、使用字面量创建对象

var p = {
    age:12,
    name:'hc',
    setAge:function(age) {
        this.age = age
    }
}
问题:
	1、代码的复用率太低了

3、使用工厂模式

function Person(name,age) {
	this.name = name
    this.age = age
}
var p = new Person()

二、继承方式

1、普通继承(只能继承方法)

// 人对象(父亲对象)
function Person(name,age) {
    this.name = name
    this.age = age
}
Person.prototype.setAge = function(age) {
    this.age = age
}
Person.prototype.constructor = Person

// 学生对象(儿子对象)
function Student(name,age,school) {
    this.name = name
    this.age = age
    this.school = school
}
Student.prototype = new Person()
Student.prototype.setSchool = function(school) {
    this.school = school
}
Student.prototype.constructor = Student
该方法存在明显的缺陷,就是父亲的很多属性变量,我们使用不了,我们只能每次自己往里面添加,因此,我们可以使用第二种组合方式来让儿子使用父亲的属性

2、组合继承

// 人对象(父亲对象)
function Person(name,age) {
    this.name = name
    this.age = age
}
Person.prototype.setAge = function(age) {
    this.age = age
}
Person.prototype.constructor = Person

// 学生对象(儿子对象)
function Student(name,age,school) {
    Person.call(this,name,age)
    this.school = school
}
Student.prototype = new Person()
Student.prototype.setSchool = function(school) {
    this.school = school
}
Student.prototype.constructor = Student
var s = new Student('zs',12,'XX大学')
console.log(s)

3、注意点

1、为什么要写Student.prototype.constructor = Student这样一句话?
	因为constructor会因为继承原因,导致值不一定对,所以为了保险起见,将constructor指向自身
2、Person.call(this,name,age)是在Student中创建变量还是用父类的变量
	实际上是在Student中创建的name和age属性,而不是借用父类的

posted on 2021-10-23 15:31  黄文超  阅读(101)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3