zoukankan      html  css  js  c++  java
  • JavaScript对象原型写法详解

        体现对象原型分步式写法

    //原型分步式写法
    //构造函数
    function Person(){}
    //对象原型
    Person.prototype.name = 'Avensatr';
    Person.prototype.age = '22';
    Person.prototype.job = 'Software Engineer';
    Person.prototype.sayName = function(){
        console.log(this.name);
    }

     我问你答?? 打印结果是??

    var person = new Person();
    //__proto__隐式原型与显式原型Person.prototype
    console.log(person.__proto__);
    console.log(Person.prototype);
    //构造函数(对象原型构造用于构造对象)
    console.log(Person.prototype.constructor);
    console.log(Person.prototype.constructor === Person); 
    //构造函数原型
    console.log(Person.prototype.constructor.prototype); 
    //对象原型
    console.log(Person.prototype.__proto__);
    //构造函数是由function Function(){}创建
    console.log(Person.prototype.constructor.__proto__);
    console.log(person.__proto__ === Person.prototype);
    

    理清上述(实例与构造原型对象关联关系)打印结果后,见图解如下

    完整图解应如下

    Person.prototype只是对象指针引用,真正创建对象的是Person.prototype.constructor.prototype 构造函数原型

    每个创建一个函数都有prototype属性,该函数prototype属性指向一个该函数创建的对象.即 Person.prototype.constructor.prototype

    实例对象之间通过“__proto_隐式原型”构造函数原型对象“Person.prototype”之间相关联 即person.__proto__ === Person.prototype

    instanceof 用于检测对象与实例之间关系

    person instanceof  Person 沿着原型链person.__proto__Person.prototype查找,若两条线能找到同一个引用,即同一个对象,则返回true,否则返回false

        体现对象原型封装的写法

    //原型集中写法
    function Person(){}
    var friends = new Person();//创建一个实例对象
    Person.prototype = {
        name : "Avensatr",
        age : "22",
        job : "Software Engineer",
        sayName : function(){
             console.log(this.name);
        }
    }
    

     这种面向对象快捷写法 Person.prototype = {} 与上述对象原型分步式写法有所区别;本质体现在原型的重写

    Person.prototype.constrctor 不再指向 function Person(){} 而指向新的function Object() { [native code] }函数

    打印结果如下图

       匿名函数自执行封装对象原型方法

    function Person(){}
    Person.prototype = (function () {
        var setName = function (name) {
             return name;
        },
        setAge = function (age) {
             return age;
        },
        setJob = function (job) {
             return job;
        };
        return {
            setName : setName,
            setAge : setAge,
            setJob : setJob
        }
    })();
    

    匿名函数自执行与体现对象原型封装的写法原理是一样的,这里不再赘述  

    作者:Avenstar

    出处:http://www.cnblogs.com/zjf-1992/p/6622444.html

    关于作者:专注于前端开发

    本文版权归作者所有,转载请标明原文链接

    【资料参考】

    http://www.sxrczx.com/docs/js/2305453.html

    JavaScript高级程序设计(第三版)

  • 相关阅读:
    [saiku] 系统登录成功后查询Cubes
    216. Combination Sum III
    215. Kth Largest Element in an Array
    214. Shortest Palindrome
    213. House Robber II
    212. Word Search II
    211. Add and Search Word
    210. Course Schedule II
    分硬币问题
    开始学习Python
  • 原文地址:https://www.cnblogs.com/zjf-1992/p/6622444.html
Copyright © 2011-2022 走看看