zoukankan      html  css  js  c++  java
  • This和Prototype定义方法的区别

    This和Prototype

    this 是指代上下文中的this对象

    1.利用this实现的方法,可以访问类中的私有变量和私有方法。而利用原型对象实现的方法,无法访问类中的私有变量和方法

    function Person(x){
      this.x = x; //变量x
      var a = "this is private";  //这个是Person中的私有变量
      //this 实现的方法
      this.hello = function() {
        console.log(a)
      }
    }
    //通过prototype实现的原型对象上的方法
    Person.prototype.say = function(){
      console.log(a)
    }
    // 生成实例
    var person1 = new Person(1)
    person1.hello()         // "this is private"
    person1.say()           // ReferenceError: a is not defined
    

    2.实例访问对象的属性或者方法时,将按照搜索原型链prototype chain的规则进行。首先查找自身的静态属性、方法,继而查找构造上下文的可访问属性、方法,最后查找构造的原型链。

    function Test(){
      this.test = function() {
        alert("defined by this")
      }
    }
    
    Test.prototype.test = function() {
      alert("defined by prototype")
    }
    var _o = new Test()
    _o.test() //"defined by this"
    

    3.“this”和“prototype”定义的另一个不同点是在内存中占用空间不同。使用“this”关键字,实例初始化时为每个实例开辟构造方法所包含的所有属性、方法和所需空间,而使用prototype定义的,由于“prototype”实际上是指向父级的引用,因此在初始化和存储上比“this”节约资源。

  • 相关阅读:
    使用Objectivec Block
    NSBundle的使用,注意mainBundle和Custom Bundle的区别
    根据名称加载界面
    java获取运行的jar(class)文件的路径
    xamppcontrol中启动Apache时80断口被占用的错误
    [转]利用location的hash值来解决Ajax两大难题
    JAVA 调用Web Service的方法
    asp.net mail
    很是无奈
    憨山大师的醒世咏
  • 原文地址:https://www.cnblogs.com/codedisco/p/14261238.html
Copyright © 2011-2022 走看看