zoukankan      html  css  js  c++  java
  • javascript prototype和__proto__

    < script type = "text/javascript" >
    function Person() {
    // 属性
    this.head = 1;
    this.eye = 2;
    // 方法
    this.eat = function () {
    alert("吃东西");
    }

    }

    //扩展类的方法

    Person.prototype.run =function(){

    alert("我会跑步");

    }


    function Programmer() {
    this.coding = function(){
    alert("我会敲代码");
    }
    }

    //扩展类的方法

    Programmer.prototype.run =function(){

    alert("我会走");

    }

    //继承
    Programmer.prototype = new Person();

    // 为子类添加新的方法
    Programmer.prototype.debug = function () {
    alert("我会调试代码");
    }

    // 调用示例
    function doCoding() {
    var a = new Programmer();
    alert(a.head); // 调用父类的属性
    a.eat(); // 调用父类的方法
    a.debug(); // 调用子类的方法
    }

    doCoding();

    var p = new Programmer();

    p.run();

    //执行Person.run() 为什么? 主要看p.__proto__指向是那个对象的__proto__。

    p.__proto__
    //Person {head: 1, eye: 2}    

    //从这里可以看出p.__proto__ 指向是Person对象,所有会执行Person.run()

    p.__proto__.run();   

    //我会跑步


    </script>

    总结:

    1、prototype 是类(函数对象)的一个属性。作用:扩展类的属性和方法、用来继承其它对象(属性和方法)

    2、__proto__是对象内部(var obj = function Person(){})的一个属性。作用:指向对象对应类的prototype

  • 相关阅读:
    Two Sum II
    Subarray Sum
    Intersection of Two Arrays
    Reorder List
    Convert Sorted List to Binary Search Tree
    Remove Duplicates from Sorted List II
    Partition List
    Linked List Cycle II
    Sort List
    struts2结果跳转和参数获取
  • 原文地址:https://www.cnblogs.com/chenweichu/p/5591987.html
Copyright © 2011-2022 走看看