Have a chat javasript inherit

Source: Internet
Author: User
Tags shallow copy

?? It's been almost 2 years or so. JavaScript, just at the beginning simply for some form validation and operation of the DOM node, and not in-depth use, with the gradual deepening, began not to write repetitive code (lazy start), thus writing simple inheritance, encapsulation, abstraction and so on, the final effect write duplicate code less , High availability (main: Fast iteration, code can be used continuously, and less overtime )

Demo constructor Declaration class
function Person(name){    this.name = name;}
New Build Instance

The disadvantage of the new build instance is that the properties and methods cannot be shared, and each new instance will open up new memory space , resulting in significant resource wastage.

var personA = new Person('小明');console.log(personA.name);

This of the constructor points to the new instance
Such as:

function Person(name){    this.name = name;    this.sex = '女'}var personA = new Person('小明');var personB = new Person('小妞');personA.sex = '男';console.log(personB.sex);  //女

Should we adopt a declarative solution here? The designer solves this problem very well, then it is the introduction of the prototype property (including object)

Prototype property

The advantage is that once an instance is created, it will automatically co-hold shared properties and methods, such as:

function Person(name){    this.name = name;}Person.prototype.sex = '女';var personA = new Person('小明');var personB = new Person('小妞');console.log(personA.sex);  //女console.log(personB.sex);  //女//证明它们是共享的Person.prototype.sex = '男';console.log(personA.sex);  //男console.log(personB.sex);  //男

You may not see the benefits of prototype here, but when you have a lot of methods and properties, are you running more efficiently? So:

function Person(name, sex){    this.name = name;    this.sex = sex,    this.country = '中国',    this.show = function(){        console.log(this.name + '的国籍是:'+this.country+',性别:'+this.sex);    }}var personA = new Person('小明'.'男');personA.show();   //小明的国籍是是中国,性别:男var personB = new Person('小妞','女');personB.show();  //小妞的国籍是是中国,性别:女

There seems to be no problem, but both persona and personb contain the same content as the country and show attribute methods, which creates a waste of space and reduces efficiency, so that we can share properties and methods

function Person(name, sex){    this.name = name;    this.sex = sex,}Person.prototype.country = '中国';Person.prototype.show = function(){    console.log(this.name + '的国籍是:'+this.country+',性别:'+this.sex);}var personA = new Person('小明'.'男');var personB = new Person('小妞','女');personA.show();   //小明的国籍是是中国,性别:男personB.show();  //小妞的国籍是是中国,性别:女

properties used with Protorype --isprototypeof (), Hasownprototype (), in

function Person(name, sex){    this.name = name;    this.sex = sex,}Person.prototype.country = '中国';Person.prototype.show = function(){    console.log(this.name + '的国籍是:'+this.country+',性别:'+this.sex);}//isPrototypeOf() 判断实例和对象之间的关系console.log(Person.prototype.isPrototype(personA))  //trueconsole.log(Person.prototype.isPrototype(personB))  //true//hasOwnPrototype() 判断属性是本地属性,还是继承自prototype属性console.log(personA.hasOwnPrototy('name'))  //trueconsole.log(personA.hasOwnPrototy('country'))  //false//in 判断是否含有属性,不管本地还是继承prototypeconsole.log('name' in personA)  //trueconsole.log('country' in personA)  //true
Constructor property

Continue to use the previous person prototype object

function Person(name){    this.name = name;}Person.prototype.sex = '女';var personA = new Person('小明');var personB = new Person('小妞');//新增的实例自动包含有constructor属性console.log(personA.constructor == Person);  //trueconsole.log(personB.constructor == Person);  //true

You can also use instanceof to determine the relationship between an instance and a prototype object.

console.log(personA instanceof Person);  //trueconsole.log(personB instanceof Person);  //true
"Inheritance" (constructor inheritance) between commonly used objects (5 types)

Suppose you now have the person and teacher two object, and want teacher to inherit someone

//Person对象function Person(name){    this.name = name;}//Teacher对象function Teacher(age,sex){    this.age = age;    this.sex = sex;}
1.: Use constructor bindings (call or Apply)
function Teacher(age,sex,name){    Person.apply(this,name);//Person.call(this,name);    this.age = age;    this.sex =sex;}
2,: Use prototype, that is, we said prototype properties, modify constructor point
Teacher.prototype = new Person('xiaoming'); //修改prototy对象原先的值Teacher.prototype.constructor = Teacher;var teacher1 = new Teacher(19,'女');
3.: Direct succession to prototype
function Person(){}person.prototype.name = "xiaoming";function Teacher(age,sex){    this.age = age;    this.sex = sex;}//Teacher的prototype对象直接指向Person的prototype对象Teacher.prototype = Person.prototype;Teacher.prototype.constructor = Teachervar teacher1 = new Teacher(19,"女");
4. Intermediary new function () {} empty Object
var Fn = new function(){};Fn.prototype = Person.prototype;Teacher.prototype = new Fn();Teacher.prototype.constructor = Teacher;//扩展封装function Extend(ChildObj,ParentObj){    var Fn = new function(){};    Fn.prototype = ParentObj.prototype;    ChildObj.prototype = new Fn();    ChildObj.prototype.constructor = ChildObj;    ChildObj.uber = ParentObj.prototype;  //直接指向父对象prototype属性}//Teacher继承PersonExtend(Teacher,Person);var teacher1 = new Teacher(19,'女');
5. Copy Inheritance (full)
function Extend(ChildObj, ParentObj) {    var p = ParentObj.prototype;    var c = ChildObj.prototype;    for (var i in p) {         c[i] = p[i];  }  c.uber = p;} //Teacher继承PersonExtend(Teacher,Person);var teacher1 = new Teacher(19,'女');
Non-constructor "inheritance" (3 types)
//原始var Person = {    name: '小明'}var Teacher ={    age:19,    sex:'女'}

Here's how we can get teacher to inherit the person

1.: Object method
function object(obj){    function Fn(){}    Fn.prototype = obj;    return new Fn();}var teacher1 = object(Person);teacher1.age = 19;teacher1.sex = '女';
2,: Shallow Copy method
function extendCopy(ParentObj){    var c = {};    for(var i in ParentObj){        c[i] = p[i];    }    c.uber = p;    return c;}//使用extendCopyvar teacher1 =  extendCopy(Person);teacher1.age = 19;teacher1.sex = '女';
3.: Deep Copy method
function extendDeepCopy(ParentObj,ChildObj){    var ChildObj = ChildObj || {};    for(var i in ParentObj){        if(typeof  ParentObj[i] === 'object'){            c[i] = (ParentObj[i].constructor === Array) ? [] : {};            extendDeepCopy(ChildObj[i],ParentObj[i]);        }else{            ChildObj[i] = ParentObj[i];        }    }    return ChildObj;}//使用var teacher1 = extendDeepCopy(Person1);teacher1.age = 19;teacher1.sex = '女';

The copyright of this article is shared by the author, welcome to reprint, must retain this paragraph statement, and give the original link, thank you!

Have a chat javasript inherit

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.