javaScript of object-oriented programming object-oriented inheritance

javaScript of object-oriented programming object-oriented inheritance

An important feature of object-oriented programming is inheritance, inherit the object A object B, object B can have behavior (methods) and state (attributes), encourages code reuse.
"Prototype object" (inherited through the JavaScript language prototype) to achieve, ES6 introduced the class ( class), refer ES6 entry .

1. Overview of the prototype object

1.1 disadvantage constructor

Prior to revisit the prototype object, look at the constructor.
JavaScript can generate a new object via constructors, properties and methods defined within an object instance constructor, each new object generated by the constructors have the same properties and behavior.

function Animal(age, name){
	if(!(this instanceof Animal)){
		return new Animal(age, name);
	}
	this.age = age;
	this.name = name;
	this.print = function(){
		console.log(this.name);
	}
}

var a1 = new Animal(2, "dog");
var a2 = new Animal(3, "cat");

// 通过构造函数生成的实例对象,都有age,name和print属性
a1; //  {age: 2, name: "dog", print: ƒ}
a2; //  {age: 3, name: "cat", print: ƒ}

The example above seems to be no problem, each animal has its own age with the name. I on the basis of the above example, to add animals to sleep, eating behavior.

function Animal(age, name){
	if(!(this instanceof Animal)){
		return new Animal(age, name);
	}
	this.age = age;
	this.name = name;
	this.print = function(){
		console.log(this.name);
	};
	this.sleep = function(){
		console.log("睡觉!");
	};
	this.eat = function(){ 
		console.log("吃东西!")
	};
}
	var a1 = new Animal(2, "dog");
	var a2 = new Animal(3, "cat");
	a1.sleep(); // 睡觉
	a2.sleep(); // 睡觉
	a1.eat(); // 吃东西
	a2.eat(); // 吃东西

	// 都具有吃东西和睡觉的行为,那么两者一样吗?
	a1.sleep === a2.sleep; // false
	a1.eat === a2.eat; // false

We see from the above example, a1and a2have eatand sleepmethods, but the two are not the same. This is due eatand sleepis generated on every instance of the object, the two instances is generated twice. I.e. each create a new instance, a new city eatand sleepmethods. So that more waste of system resources, because all eatand sleepmethods are the same behavior, each instance should be shared.

This can be through the "prototype object" ( prototypeto be resolved).

1.2 prototype property

JavaScript inheritance mechanism design idea is that all the properties and methods of the prototype object can be instantiated object sharing.
JavaScript provides that each function has a prototypeproperty, point to an object.

function f(){}
typeof f.prototype; // "object"

In the above code, the function fdefault having prototypeattribute to an object.

For the constructor, the generated instances when the attribute is automatically become the prototype of the object instance.

function Animal(name){
	this.name = name;
}

// 原型对象设置公共的属性sex
Animal.prototype.sex = 1 ;

typeof Animal.prototype; // "object"

var a1 = new Animal("cat");
var a2 = new Animal("dog");

a1.sex; // 1
a2.sex; // 1 

The above code, the constructor Animalof the prototypeproperty of the object pointed to, that is, a1and a2the prototype object, in a prototype object to add the above sexproperties, can share the object instance sexattribute.

Properties of the prototype object instance is not a property of the object itself. As long as the modified prototype object, change will be immediately reflected in all instances of objects.

// 原型对象修改sex
Animal.prototype.sex = 0 ;

// 每个实例的sex发生改变
a1.sex; // 0
a2.sex; // 0 

As an example, when the object itself is not a property or method, it will go to the prototype object to find this property or method. If there is an instance of an object property or method itself, it will not go looking for this prototype object property or method.

a1.sex = 2;

a1.sex; // 2
a2.sex ; // 0
Animal.prototype.sex; // 0 

In summary, the role of the prototype object, is to define the properties and methods shared by all instances of objects.

1.3 prototype chain

JavaScript provides that all objects have their own prototype object ( prototype). On the one hand, any object can act as prototype of other objects; on the other hand, since the prototype objects are objects, so it also has its own prototype. Thus, it will form a "prototype chain": object to the prototype, the prototype of the prototype and then ......

If the layers of traced, the prototype of all objects can ultimately be traced back to Object.prototypethat Objectconstructor prototypeproperty that points to an object. That is, all objects inherit the Object.prototypeproperties.

In fact, Object.prototypealso has its own prototype, its prototype null. nullWe do not have any properties and methods, do not own prototype. Therefore, the prototype chain is at the end null.

Object.getPrototypeOf(Object.prototype); // null

Then to complete the prototype chain as shown below:

对象
原型对象
原型对象的原型对象
.....
Object.prototype
null

When reading an attribute of an object, JavaScript engine to find the properties of the object itself, if not, go on to its prototype, if this fails, go on to the prototype of the prototype. If until the top level Object.prototypestill can not find, then return undefined. If the object itself and its prototype, defines a property of the same name, then the priority read object's own properties, this is called "covering."

Note: looking for a property on the prototype chain, the performance is influential, the more property in the prototype chain upstream, the greater the impact on performance. If you find a property that does not exist, it will traverse the entire prototype chain.

1.4 constructor property

prototypeObject has a constructorproperty, pointing to default prototypeconstructor object is located.

function P() {}
P.prototype.constructor === P // true

constructorProperties also defines the prototypeobjects above, it is intended that all instances of objects can inherit.

function F(){}

var f1 = new F();

//prototype对象的constructor属性默认指向prototype对象所在的构造函数
f1.constructor === F; // true
f1.constructor === F.prototype.constructor; // true

Then the constructorproperty has what effect?

  1. By constructorproperty which is determined in the end instance object generated constructor.
function F(){}
var f1 = new F();

f1.constructor;//F(){}
  1. By constructorproperty, a new instance of the object can be another instance of the object.
function F(){}
var f1 = new F();

// 通过constructor属性新建另一个实例对象
var f2 = new f1.constructor();
f2 instanceof F; // true

constructorProperty indicates the relationship between the prototype object constructor, if you modify the prototype object, but also modify the general constructorproperties that prevent quoted wrong time.

function F(){};
F.prototype.constructor === F; // true

// 修改原型对象为一个数组对象
F.prototype = new Array();

F.prototype.constructor === F; // false
F.prototype.constructor === Array; // true

The above code, the modified Fprototype object, but not modify the constructorproperties, leading to constructorproperty is no longer directed F.

When modifying the prototype object, preferably a modified constructorproperty.

function F(){}

// 不推荐写法,没有修改contructor属性
F.prototype = {
	method1: function (...) { ... },
	...
}

// 推荐写法,constructor属性重新指向原来的构造函数
F.prototype = {
	constructor: F,
	method1: function (...) { ... },
	...
}

// 更好的写法,只在原型对象上面添加方法
F.prototype.method1 = function(...){...}

2. instanceof operator

instanceofOperator returns a Boolean value indicating whether the object is an instance of a constructor. instanceofLeft operator is an object instance, the right side is the constructor.

var v = new Vehicle();
v instanceof Vehicle // true

instanceofOperator is substantial: check whether the right prototype object constructor prototype chain on the left side of the object instance. Therefore, the following two are equivalent wording.

function F(){}
var f = new F();

f instanceof F; // true
//等价于
F.prototype.isPrototypeOf(f); // true

Because instanceofchecks prototype whole chain, the same instance of an object, a plurality of constructors may be returned true.

var now = new Date();

now instanceof Date; // true
now instanceof Object; // true
// 等价于
Date.prototype.isPrototypeOf(now);
Object.prototype.isPrototypeOf(now);

instanceofOperator can be used type judgment value.

var person = {
	name: "jidi",
	age: 22
}
var arrays = ["I","love","java"];

person instanceof Object; // true
arrays instanceof Array; // true

instanceofOperator can be used is determined whether the value of a non- nullobject, since all objects are Objectinstances, except null.

var person = {
	name: "jidi",
	age: 22
}

// 判断一个值是否是非null对象
person instanceof Object; // true
null instanceof Object; // false

Note: Theinstanceof operator can only be used for an object, the value of the original type is not applicable. But also for nulland undefinedalways return false.

3. inherit constructors

Too late, I could not stand up, have time to write back ...

Released six original articles · won praise 3 · Views 1502

Guess you like

Origin blog.csdn.net/qq_41863849/article/details/103964869