zoukankan      html  css  js  c++  java
  • JavaScript 学习之原型与函数

    1. 首先,所有对象都是通过构造函数产生的。所以任何对象的.constructor属性,指向其构造函数。

    2. 只有函数才有prototype属性,用来定义,以它为构造函数所构造出来的对象,具有prototype所定义的一切属性和方法。

    3. 函数的.prototype定义的所有属性和方法,和该函数本身无关,只和使用该函数构造出来的对象有关。

    4. 每个对象的__proto__属性,表明了该类对象的类型。属性的值是其.constructor的prototype。

    5. 在调用对象的成员函数时,如果该成员函数不是该对象本身定义的,而是原型继承来的(也就是说这个属性/方法来自于是该对象构造函数的原型)那么就会顺着obj.__proto__找到该方法。

    6. 有一个特殊的对象,该对象的__proto__是null,这个就是object的始祖(我称之为始祖对象,其实他是Object.prototype)

    7. 在创建一个函数foo()后,foo的constructor是Function对象。foo的__proto__当然就是Function.prototype;而foo的prototype是唯一的!是编译器附加给他的,是一个Object类型。foo.prototype是从Object()构造的,所以foo.prototype.__proto__是Object.prototype(就是始祖对象)。

    ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    始祖对象定义了对象的根本方法,即:

    __defineGetter__ [Function]  (id=65)
    __defineSetter__ [Function]  (id=66)
    __lookupGetter__ [Function]  (id=71)
    __lookupSetter__ [Function]  (id=74)
    constructor [Function]  (id=19)
    hasOwnProperty [Function]  (id=68)
    isPrototypeOf [Function]  (id=70)
    propertyIsEnumerable [Function]  (id=69)
    toLocaleString [Function]  (id=72)
    toString [Function]  (id=73)
    valueOf [Function]  (id=67)
    __proto__ null

    所以呢,JS世界里面的所有对象,都自动继承了这些方法。

    ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    函数的默认原型是什么样的呢?

    var A = function() {};
     A.prototype.constructor == A; //true
     var a = new A();
     a.constructor == A; //true (a's constructor property inherited from it's prototype)

    ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    这个例子很有用!

    //Constructor. <em>this</em> is returned as new object and its internal [[prototype]] property will be set to the constructor's default prototype property
    varCircle = function (radius) {
        this.radius = radius;
        //next line is implicit, added for illustration only. this指针这个时候指向的是正在构造的对象。
        //this.__proto__ = Circle.prototype;
    }


  • 相关阅读:
    linux centos7 安装mysql-5.7.17教程(图解)
    java中equals,hashcode和==的区别
    常用正则表达式大全
    MyEclipse中的重命名
    MyEclipse中查询
    Java中的代理模式
    Java中的枚举
    Java中的异常-Throwable-Error-Exception-RuntimeExcetpion-throw-throws-try catch
    eclipse将编辑栏一分为二
    图的存储,搜索,遍历,广度优先算法和深度优先算法,最小生成树-Java实现
  • 原文地址:https://www.cnblogs.com/puncha/p/3877012.html
Copyright © 2011-2022 走看看