Creating objects and implementing inheritance in JavaScript

Source: Internet
Author: User
Tags hasownproperty

# oo

# #创建对象

1. Relationships between prototypes, constructors, and instances

* The Construct-> constructor of the prototype; call the isPrototypeOf (obj) method to determine the relationship with the instance;
* Prototype-> prototype of the constructor function;
* __PROTO__ prototype for instance (only exists in Chrome,safari,firefox, but common [[prototype]]); the getprototypeof () method can return the value of [[prototype]];
* Constructor after the constructor's ' subclass ' new generates an instance, you can use the instanceof operator to detect whether the constructor appears on the prototype chain.

2. Description:

* A function will have a prototype object after declaration, and the object's constructor property holds a pointer to the function.
* To assign a value to the prototype, let the pointer in the prototype point to a new object, and the constructor property will be lost naturally. If the value of the parent class is assigned to it, then the constructor is the value of the parent class instance. The parent class instance does not have this property and inherits the constructor from the parent class's prototype. Therefore, the value of the subclass constructor (This.constructor) is obtained by this step:

Subclass Instance (no)--subclass prototype (NO)--parent class prototype (with, for parent class constructor)

3. Understanding of the New keyword

The role of new is to create a new scope, point this to the scope, and then execute the code in the function. Without the new keyword, this will point to the Globle object, which is the window object in the browser.

4. Detecting the relationship between objects and attributes

(1)

The * in operator can access this property
* hasOwnProperty () exists in the instance
*!obj.hasownproperty () && in existing prototype

(2)

* For-in Loop enumerates the attributes in the containing instance and the enumerable attributes in the prototype;
* Object.keys (obj) returns an array of enumerable instance properties;
* Object.getownpropertynames (obj) Gets all instance properties, whether or not it can be enumerated;




# #实现继承

1. Prototype chain inheritance

2. Borrowing constructors (also known as forged objects, object impersonation, classic inheritance, etc.)

3. Combination inheritance (also known as pseudo-classical inheritance)

function Anm (name,age) {
THIS.name = name;
This.age = age;
}
Anm.prototype.sayBye = function () {
Console.log (THIS.name + ' say bye to you! ');
};
function Dog (food, name, age) {
Inherit a property from a parent class by using the call or Apply method
Anm.call (this, name, age);
This.food = food;
}
Subclasses inherit methods by setting the prototype equal to one instance of the parent class
Dog.prototype = new Anm ();
Dog.prototype.constructor = Dog;
Dog.prototype.sayHello = function () {
Console.log (this.name + ' Say hello to me! ')
};
Dog1 = new Dog (' Shit ', ' Little Yellow Dog ', 15);
Console.log (DOG1); {name: "Little Yellow Dog", age:15, Food: "Shit", Constructor:function, Sayhello:function ...}
Dog1.saybye (); Small yellow Dog say bye to you!
Dog1.sayhello (); Little yellow Dog say hello to me!

This inheritance enables instances of subclasses to have their own properties, and can inherit common methods from the prototype of the parent class. So it becomes the most common inheritance pattern in JavaScript.


4. prototype-Type Inheritance

function Anm (Klass) {
This.klass = Klass;
}
var dog1 = object.create (Gou, {
Name: {
Configurable:true,
Enumerable:true,
Writable:true,
Value: ' Xiao Huang '
},
Birthyear: {
value:2012
},
Age: {
Get:function () {
var thistime = new Date ();
Return Thistime.getfullyear ()-this.birthyear;
}
}
});
Console.log (' Pre-Modified object ');
Console.log (DOG1); Object {name: "Xiao Huang", birthyear:2012, Age:3, Klass: "Dog"}
Dog1.name = ' Xiao Li ';
Dog1.birthyear = 2010;
Console.log (' modified object '); Object {name: "Xiaoli", birthyear:2012, Age:3, Klass: "Dog"}
Console.log (DOG1);

The Object.create () method accepts two parameters, the first is the object as a prototype, and the second is the object for which the new team wants to define additional attributes, in JSON format, each property to be added is a property in the object, and its value is also a descriptor object.

Property has data properties (such as name and birthyear above) and accessor properties (such as age above), if only one attribute is written, the value of the remaining attribute will be set to false. So the above birthyear is impossible to change.

This can be used in situations where a pointer keeps an object similar to another object, without having to create the constructor.

5. Parasitic inheritance

The Object.create () method above can only create the first parameter, then add properties to the returned function and encapsulate the entire process, which is called parasitic inheritance.

6. Parasitic combined inheritance

The prototype of the subclass in Dog.prototype = new Anm () was added to the Anm attribute Klass (the value undifiend), while the dog constructor also adds Klass to the instance, which is equivalent to creating attributes in both the prototype and the instance. If there are many attributes, it is a waste. It is possible to inherit the method of the parent class if it is possible to let the child class prototype produce these attributes and direct his [[prototype]] Pointer to the parent class's prototype.
Let's wrap a method first:

function Inheriyprototype (subtype, supertype) {
var newprototype = object.create (Supertype.prototype);
Subtype.prototype = Newprototype;
Newprototype.constructor = subtype; Rewrite the Subtype.prototype and lost his constructor, here to write
}

This method lets the subclass not assign a value through an instance of the parent class, but instead makes its [[prototype]] direct point to the instance of the parent class.

In fact, the prototype of this subclass is created by an empty function, and the prototype of the empty function equals the prototype of the parent class. So let the instance of this empty function have only one [[prototype]], then assign this instance to the prototype of the subclass, plus the constructor attribute. It realizes the purpose of not creating superfluous attributes.

Next:

function Anm (Klass) {
This.klass = Klass;
}
Anm.prototype.sayKlass = function () {
Console.log (This.klass);
};
function Dog (name, Klass) {
Anm.call (this, Klass);
THIS.name = name;
}
Inheriyprototype (Dog, Anm);
var dog1 = new Dog (' Small yellow ', ' canine ');
Console.log (DOG1); Dog {klass: "canine", Name: "Xiao Huang", Constructor:function, sayklass:function}
Dog1.sayklass (); Canine Animals
Console.log (Dog.prototype); Dog {constructor:function, sayklass:function}
Console.log (Dog.prototype.isPrototypeOf (DOG1)); True
Console.log (Anm.prototype.isPrototypeOf (DOG1)); True

Now many programmers generally believe that parasitic combination is the most ideal inheritance paradigm. Some of the methods in Yui have already begun to be used.

Creating objects and implementing inheritance in JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.