JavaScript学习笔记(九)对象

1.理解对象

// 1.数据属性
configurable(delete)
enumerable(for in)
writable(update)
value

// 2.访问器属性
configurable(delete)
enumerable(for in)
get
set

Object.defineProperty(obj, prop, descriptor)
Object.defineProperties(obj, descriptors)

Object.getOwnPropertyDescriptor(obj, prop)
Object.getOwnPropertyDescriptors(obj)

2.创建对象

// 1.工厂模式
// 2.构造函数
// 构造函数创建对象的步骤
(1)创建一个新对象
(2)this只想新对象
(3)执行函数代码
(4)返回新对象(如果没有返回的话)
// 3.原型模式
//
constructor person1.constructor === Person person1 instanceof Person Person.prototype.constructor === Person person1.__proto__ === Person.prototype Person.prototype.isPrototypeOf(person1) Object.getPrototypeOf(person1) === Person.prototype person1.hasOwnProperty('name') // 实例属性(可枚举和不可枚举) in // 实例属性和继承属性(可枚举和不可枚举) for in // 实例属性和继承属性(可枚举) Object.keys(obj) // 实例属性(可枚举) Object.getOwnPropertyNames(obj) // 实例属性(可枚举和不可枚举) // 调用构造函数时会为实例添加一个指向最初原型的__proto__指针,把原型修改为另一个对象就等于切断了构造函数与原型之间的联系。实例中的指针仅指向原型,而不指向构造函数。
// 4.组合构造函数和原型
function Person(){}
Person.prototype = {}
// 5.动态原型
function Person(name, age) {
  this.name = name
  this.age = age
  if (typeof this.sayName !== 'function') {
    Person.prototype.sayName = function() {
      console.log(this.name)
    }
  }
}
// 6.寄生构造函数
function specialArray() {
  values = new Array()
  values.push.apply(values, arguments)
  values.toPipedString = function() {
    return this.join('|')
  }
  return values
}

3. 继承

// 1.借用构造函数
function SuperType(name) {
  this.name = name
  this.colors = ['red', 'green']
}
function SubType(name) {
  SuperType.call(this, name)
}
// 2.组合继承
function SuperType(name) {
  this.name = name
  this.colors = ['red', 'green']
  this.sayName = function() {
    console.log(this.name)
  }
}
function SubType(name) {
  SuperType.call(this, name)
}
SubType.prototype = new SubType()
SubType.prototype.sayAge = function() {
  console.log(this.age)
}
原文地址:https://www.cnblogs.com/zhoulixue/p/10816394.html