红宝书第六章 面向对象编程

  • ECMA-262 defines an object as an “unordered collection of properties each of which contains
    a primitive value, object, or function.”

UNDERSTANDING OBJECTS

  • Data Properties
    • the default property attributes: Configurable Enumerable Writable Value
    • setting configurable to false means that the property cannot be removed from the object.
    • Object.defineProperty()
  • Accessor Properties
    • Configurable Enumerable Get Set
  • Defining Multiple Properties Object.defineProperties()
  • Object.getOwnPropertyDescriptor()

Object Creation

The Factory Pattern

function createPerson(name, age, job){
	var o = new Object();
	o.name = name;
	o.age = age;
	o.job = job;
	o.sayName = function(){
		console.log(this.name);
	};
	return o;
}
var person1 = createPerson("Nicholas", 29, "Software Engineer");
  • With no way to define classes in ECMAScript,developers created functions to encapsulate the creation of objects with specific interfaces
  • this solved the problem of creating multiple similar objects
  • the factory pattern didn’t address the issue of object identification (what type of object an object is)

The Constructor Pattern

function Person(name, age, job){
	this.name = name;
	this.age = age;
	this.job = job;
	this.sayName = function(){
		console.log(this.name);
	};
}
var person1 = new Person("Nicholas", 29, "Software Engineer");
console.log(person1.constructor == Person)
console.log(person1 instanceof Object)
console.log(person1 instanceof Person)
  • with the following exceptions:
    • There is no object being created explicitly
    • The properties and method are assigned directly onto the this object
    • There is no return statement.
  • Constructors as Functions
    • constructors in ECMAScript are used to create specific types of objects
    • constructors are simply functions that create objects
    • Any function that is called with the new operator acts as a constructor
  • Problems with Constructors
    • methods are created once for each instance

为了性能,尽量避免使用__prototype__

  • 作为setter属性时:用Object.create()代替__proto__
    Dog.prototype.proto = EventEmitter.prototype;
    写成Dog.prototype = Object.create(EventEmitter.prototype)

  • 作为getter属性时:Object.getPrototypeOf()代替之。比如:
    Cat.prototype.__proto__ === Object.getPrototypeOf(Cat.prototype)

  • prototype对象是实例的原型对象,被实例继承,那__proto__是什么?

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值