原型与继承

一级目录

原型的初步认识

let arr = ['thinker','thinker'];
console.log(arr.concat("wing"));

let Thinker = {};
console.log(Thinker);
let  Wing = {};
console.log(Object.getPrototypeOf(Thinker) == Object.getPrototypeOf(Wing));
//true

没有原型的对象也是存在的

let thinker = {name:"thinker"};
console.log(thinker.hasOwnProperty("name"));
//为true
// 完全数据字典对象
let wing =Object.create(null,{
    name: {
        value:"hdr"
    }
});
    console.log(wing.hasOwnProperty("name"));
    //可以创建没有原型的对象  所以会报错

原型方法与对象方法优先级

    //就近原则 自己有 就不需要向上级去借
let thinker = {
    show(){
        console.log("1");
    },
    render(){
        console.log("2");
    }
};
console.log(thinker);
// {show: ƒ, render: ƒ}
//     render: ƒ render()
//     show: ƒ show()
//     __proto__: Object
thinker.__proto__.render = function () {
    console.log("3");
};
thinker.render(); //2


函数拥有多个长辈

Javascript中所有的对象都是Object的实例,并继承Object.prototype的属性和方法,也就是说,Object.prototype是所有对象的爸爸。
在对象创建时,就会有一些预定义的属性,其中定义函数的时候,这个预定义属性就是prototype,这个prototype是一个普通的对象。
而定义普通的对象的时候,就会生成一个__proto__,这个__proto__指向的是这个对象的构造函数的prototype.
__proto__一般服务于函数对象,prototype服务于函数实例化对象

//函数其实也是对象
    // prototype也是长辈
function user() {}
//把函数当对象调用的时候可以用这种方法
user.__proto__.view = function () {
    console.log("this is view function");
};
user.view();  // 打印this is view function
    // _proto_ 服务于函数对象
    // prototype 服务函数实例化的对象
    console.dir(user);
    user.prototype.show = function(){
    console.log("this is show function");
    };
let TK  =new user();
TK.show(); //this is show function
console.log(user.prototype==TK.__proto__); //true


函数有爸爸还有爷爷 父级上面还有父级 对象就一个父级

let dx = {}; //object
    function f() {} 
    console.dir(f)
    console.dir(dx)
    console.log(dx.__proto__ == Object.prototype); //true
    console.log(f.__proto__ == Object.prototype);  //false
console.log(f.__proto__.__proto__ == Object.prototype); //true

js中的prototype和__proto__的区别:

方法(Function)方法这个特殊的对象,除了和其他对象一样有上述proto属性之外,还有自己特有的属性——原型属性(prototype),这个属性是一个指针,指向一个对象,这个对象的用途就是包含所有实例共享的属性和方法(我们把这个对象叫做原型对象)。原型对象也有一个属性,叫做constructor,这个属性包含了一个指针,指回原构造函数。
Function的__proto__指向其构造函数Function的prototype;
Object作为一个构造函数(函数对象),所以他的__proto__指向Function.prototype;
Function.prototype的__proto__指向其构造函数Object的prototype;
Object.prototype的父级指向null(尽头) 顶级原型
文字看着很晕 可以自己尝试打印几次

  function A(a) {
        this.a = a;
    }
    A();
    console.log(A.prototype); //{constructor: ƒ}
    console.log(A.prototype.__proto__);
    console.log(Object.prototype.isPrototypeOf(A));//true 方法用于测试一个对象是否存在于另一个对象的原型链上
    console.log(A instanceof Object);//true
    // instanceof判断一个对象是不是某个类型的实例
    console.log(Object.prototype==A.__proto__.__proto__); //true
     console.log(Object.prototype ==A.prototype.__proto__);//true A的prototype对象的构造函数是Object.prototype   A.__proto__.__proto__和A.prototype.__proto__是一个父级 Object.prototype
     //objcet 的__proto__只服务于自己
    console.log(Object.prototype.__proto__); //null 尽头了 object原型没有父级了 为顶级原型
        console.log(__proto__===constructor.prototype);//true
       // 大多数情况下,__proto__可以理解为“构造器的原型”,即__proto__===constructor.prototype,但是通过 Object.create()创建的对象有可能不是, Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__。

下面用个很简单的例子,在object中定义的方法 实例一个新的函数 照样可以调用object的方法 因为都在一个链条上

    let obj = new Object();
    Object.prototype.show = function () {
        console.log("thinker");
    };
    function user() {}
    let wing = new user;
    wing.show(); //thiker

自定义对象的原型设置

let s = {name:"son"};
let d = {
    name:"daddy",
    show(){
        console.log("this is daddy method :" + this.name);
    }
};
Object.setPrototypeOf(s,d);
s.show(); //this is daddy method :son 借用了父亲的方法
d.show(); //this is daddy method :daddy
console.log(Object.getPrototypeOf(s)); //获取

constructor引用

function user(name) {
    this.name = name;
}
user.prototype.show=function(){
  console.log(this.name);
};
let thinker = new user.prototype.constructor("thinker")
thinker.show(); //thinker
function user(name) {
    this.name = name;
}
user.prototype = {
    constructor:user,
    show(){
        console.log(this.name);
    }
};
let thinker = new user.prototype.constructor("thinker");
thinker.show(); //thinker
function user(name) {
    this.name = name;
    // this.show = function () {
    //     console.log(this.name);
    // }
}
// user.prototype.show=function() {
//     console.log(this.name);
// };
user.prototype = {
    constructor:user,
    show(){
        console.log(this.name);
    }
};
let thinker = new user("thinker");
console.log(thinker);
function createByObject(obj, ...args) {
        const  constructor = Object.getPrototypeOf(obj).constructor
        return new constructor(...args)
}
let tk = createByObject(thinker,"1");
let tkk = createByObject(thinker,"2");
tk.show();
tkk.show();
    console.dir(tk);
    console.dir(tkk);

hasOwnProperty 和 in 属性检测差异

  1. hasOwnProperty 方法用于判断对象“自身”是否有某个属性:

  2. in 用于判断对象“自身”及其“继承对象”是否具有某个属性:

   let a = {thinker:"thinker"};
    let b = {name:"wing"};
    //in 是会攀升原型链的  
    Object.prototype.web="www.baidu.com";
    console.log("web" in a);//true
    Object.setPrototypeOf(a,b);
    console.log("name" in a); //true
    console.log(a.hasOwnProperty("name"));//false
    for (const key in a){
        if (a.hasOwnProperty(key)){
            console.log(a[key]);//只有 thinker
        } 
    }
    for (const key in a){
        console.log(key);// thinker  name  web
    } 

改变构造函数不是继承 继承是原型的继承

改变构造函数会覆盖了上面的方法 都共用到同一个原型上了

 function user() {}
 user.prototype.name=function () {
     console.log("user.name");
 };
function admin() {}
admin.prototype = user.prototype;
 admin.prototype.role = function () {
     console.log("admin.name");
 };
 function member(){}
 member.prototype = user.prototype;
 member.prototype.role = function(){
     console.log("member.name");
 };
let a = new admin();
let b = new member();
 a.role(); //member.name
 b.role();//member.name   

继承是原型的继承

 function user() {}
 user.prototype.name=function () {
     console.log("user.name");
 };
function admin() {}
admin.prototype.__proto__ = user.prototype;
 admin.prototype.role = function () {
     console.log("admin.name");
 };
 function member(){}
 member.prototype.__proto__ = user.prototype;
 member.prototype.role = function(){
     console.log("member.name");
 };
let a = new admin();
let b = new member();
 a.role();  //admin.name;
 a.name();  //user.name
 b.role(); //member.name
 b.name(); //user.name

实例化出一个新的对象

function f(){}
let obj = new f();
// 给我一个对象可以实例化出一个新的对象
let obj2 = obj.__proto__.constructor;
// console.log(obj.__proto__.constructor);
console.log(obj2);
console.log(obj);

多态

function user() {}
user.prototype.show = function () {
    console.log(this.description());
};
function admin() {}
admin.prototype = Object.create(user.prototype);
admin.prototype.description = function () {
    return "admin"
};
function member() {}
member.prototype = Object.create(user.prototype);
member.prototype.description = function () {
    return "member"
};
function vip() {}
vip.prototype = Object.create(user.prototype);
vip.prototype.description = function () {
    return "vip"
};
for (const obj of [new admin,new vip,new member]) {
    obj.show(); // admin vip member
}

原型工厂封装

function extend(sub,sup) {
    sub.prototype = Object.create(sup.prototype);
    Object.defineProperty(sub.prototype,"constructor",{
        value:sub,
        enumerable:false // 禁止被遍历
    })
    //Object.defineProperty() 方法会直接在一个对象上定义一个新属性,
    // 或者修改一个对象的现有属性,并返回此对象。
}
function user(name,age) {
     this.name = name;
     this.age = age;
}
user.prototype.show = function () {
    console.log(this.name,this.age);
}
function admin(...args) {
    user.apply(this,args)
}
extend(admin,user);
let a = new admin("thinker",19);
let b = new admin("wing",19);
a.show(); //thinker 19
b.show(); //wing 19

mixin实现多继承

mixin简单通俗的讲就是把一个对象的方法和属性拷贝到另一个对象上,注意这个继承还是有区别的。js是一种只支持单继承的语言,毕竟一个对象只有一个原型,如果想实现多继承,那就简单暴力的把需要继承的父类的所有属性都拷贝到子类上,就是使用mixin啦。

   function extend(sub,sup) {
        sub.prototype = Object.create(sup.prototype);
        Object.defineProperty(sub.prototype,"constructor",{
            value:sub,
            enumerable:false // 禁止被遍历
        })
        //Object.defineProperty() 方法会直接在一个对象上定义一个新属性,
        // 或者修改一个对象的现有属性,并返回此对象。
    }
    function user(name,age) {
        this.name = name;
        this.age = age;
    }
    user.prototype.show = function () {
        console.log(this.name,this.age);
    }
    function admin(...args) {
        user.apply(this,args)
    }
    extend(admin,user);
    const request = {
        ajax(){
           return "请求后台:"
        }
    }
 const address ={
        __proto__:request,
     getAddress(){
            // super = this __proto_
         console.log(this.__proto__.ajax() +"获取地址");
         console.log(super.ajax()+"获取地址");
     }
 }
 const credit = {
     total(){
         console.log("score");
     }
 }

 function user(name,age) {
     this.name = name;
     this.age = age;
 }

user.prototype.show = function(){
     console.log(this.name,this.age);
}

 function admin(name,age) {
     user.call(this,name,age)
 }
extend(admin,user);
 admin.prototype = Object.assign(admin.prototype,request,credit)
function member(name,age) {
    user.call(this,name,age)
}
extend(member,user)
    member.prototype = Object.assign(member.prototype,request,credit,address)
    let a = new admin("a",18);
    let b = new member("b",19);
    a.show(); //a 18
    b.show(); // b 19
 console.dir(a);
 console.dir(admin);
    a.total(); //score
    // a.getAddress(); //address 的函数方法
    //  这边打印 is not a function 因为没有放进去
    b.total();//score
    b.getAddress();//请求后台:获取地址

使用一个小案例总结

NodeList 对象
我们可通过节点列表中的节点索引号来访问列表中的节点(索引号由0开始)。
节点列表可保持其自身的更新。如果节点列表或 XML 文档中的某个元素被删除或添加,列表也会被自动更新。

在这里插入图片描述

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        section{
            width: 200px;
            height: 200px;
            background: #5CB169;
            display: inline-block;
        }
        main {
            width: 200px;
            height: 200px;
            overflow: hidden;
        }
    </style>
</head>
<body>
<main class="tab1">
    <nav>
        <a href="javascript: " style="text-decoration:none;.">one</a>
        <a href="javascript: " style="text-decoration:none;.">two</a>
        <a href="javascript: " style="text-decoration:none;.">three</a>
    </nav>
   <section style="background: grey">1</section>
    <section style="background: #0077aa">2</section>
    <section style="background: #5cb85c">3</section>
</main>


</body>
<script>
    function extend(sub, sup) {
        sub.prototype = Object.create(sup.prototype);
        sub.prototype.constructor = sub;
    }

    //动作类
    function Animation() {}
    Animation.prototype.show = function() {
        this.style.display = "block";
    };
    //隐藏所有元素
    Animation.prototype.hide = function() {
        this.style.display = "none";
    };
    //必变元素集合背景
    Animation.prototype.background = function(color) {
        this.style.background = color;
    };

    //选项卡类
    function Tab(tab) {
        this.tab = tab;
        this.links = null;
        this.sections = null;
    }
    extend(Tab, Animation);
    Tab.prototype.run = function() {
        this.links = this.tab.querySelectorAll("a");
        this.sections = this.tab.querySelectorAll("section");
        this.bindEvent();
        this.action(0);
    };
    //绑定事件
    Tab.prototype.bindEvent = function() {
        this.links.forEach((el, i) => {
            el.addEventListener("click", () => {
                this.reset();
                this.action(i);
            });
        });
    };
    //点击后触发动作
    Tab.prototype.action = function(i) {
        this.background.call(this.links[i], "#e67e22");
        this.show.call(this.sections[i]);
    };
    //重置link与section
    Tab.prototype.reset = function() {
        this.links.forEach((el, i) => {
            this.background.call(el, "#95a5a6");
            this.hide.call(this.sections[i]);
        });
    };

    new Tab(document.querySelector(".tab1")).run();
</script>


</html>
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值