首页 > Web开发 > 详细

JS_对象原型链

时间:2020-06-26 20:40:58      阅读:71      评论:0      收藏:0      [点我收藏+]


## 面向对象  extends

    -实例属性,公共属性

//实例属性

function Person(){

    this.name = ‘zs‘; 

}

let p1 = new Person();

p1.name;

//公共属性

Person.prototype.eat = function(){

    console.log(‘‘);

}

p1.eat();

//代码复用

function Student() {

    //Person();  //错误用法

    Person.call(this);

}

let s1 = new Student; // = new Student();

============================传参=========================

## 面向对象  extends

    -实例属性,公共属性

//实例属性

function Person(name){

    this.name = ‘zs‘; 

}

let p1 = new Person(‘macro‘);

p1.name;

//公共属性

Person.prototype.eat = function(){

    console.log(‘‘);

}

p1.eat();

//代码复用

function Student(name) {

    //Person();  //错误用法

    Person.call(this,name);  //支持传参

    Person.apply(this,[name]);  // apply传参必须是数组对象

}

let s1 = new Student(‘macro‘);

==========================原型链查找机制==============================

?如何继承公共属性:eat()

prototype & __proto__

[1]每个函数都一个属性名字:prototype(原型),值是一个对象(引用)——但是普通函数没有很大意义; 字符串等其他则没有

[2]绝大多数对象都有__proto__属性,指向所属类的原型(即:构造函数的原型)

    ex: s1.__proto__ === Student.prototype

        ‘macro‘.__proto__ === String.prototype

        [].__proto__ === Array.prototype

        s1.__proto__.__proto__ === Object.prototype

        Object.prototype.__proto__ = null  //终止循环

        Object.__proto__ === Function.prototype

        Function.__proto__ === Function.prototype

        Object.__proto__ === Function.__proto__

    原型 constructor 指向 构造函数

        s1.constructor  ===  Student.prototype.constructor

[3]

  -直接对子类原型赋值有问题

    Student.prototype = Person.prototype;

    缺点:更改Student的原型

    Student.prototype.constructor = Student;

    缺点:更改Person的原型

  -3种比较合适的方法:

[1]Student.prototype.__proto__ = Person.Prototype;

        Student.prototype.study = function(){

            log(‘working hard‘);

        }

        -相当于原型链

[2]Object.create()

        Student.prototype = Object.create(Person.prototype);

        // __proto__ : Person.prototype

        function create(parentProtype){

            function Fn(){}

            Fn.prototupe = parentProtype;

            return new Fn();

        }

        Student.prototype = Object.create(Person.prototype) //

                                __proto__

        s1.eat(); // === new Fn() --> Fn.prototype === parentPrytype

        所有:缺点: 是Student.constructor === Person

        改进:

            Student.prototype = Object.create(Person.prototype,{

                constructor:{

                    value:Student

                }

            });

    [3] setPrototypeOf 

        Object.setPrototypeOf(s1,Person.prototype)

JS_对象原型链

原文:https://www.cnblogs.com/macro-renzhansheng/p/13196150.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!