zoukankan      html  css  js  c++  java
  • JS中的 new 操作符简单理解

    首先上一一个简单的 new 操作符实例


    1. var Person = function(name){
    2.     this.name = name;
    3.     this.say = function(){
    4.         return "I am " + this.name;
    5.     };
    6. }
    7. var nyf = new Person("nyf");
    8. nyf.say();
     
    简单来说,上述例子中,以 new 操作符调用构造函数的时候,函数内部发生以下变化:
      1、创建一个空对象,并且 this 变量引用该对象,同时还继承了该函数的原型。
      2、属性和方法被加入到 this 引用的对象中。
      3、新创建的对象由 this 所引用,并且最后隐式的返回 this 。
     
    以上情况在 new 操作符调用下,后台就相当于 

    1. var Person = function(name){
    2.     //var this = {};
    3.     this.name = name;
    4.     this.say = function(){
    5.         return "I am " + this.name;
    6.     };
    7.     //return this;
    8. }
    对于以上的讲述不知道有没有讲清楚。
     

    1. var obj = new Base();
    相当于运行以下代码

    1. var obj = {};
    2. obj.__proto__ = Base.prototype;
    3. Base.call(obj);
    对于ES5中添加了 Object.create(),

    1. if(typeof Object.create !== "function"){
    2.     Object.create = function(o){
    3.         function F(){};
    4.         F.prototype = o;
    5.         return new F();
    6.     }
    7. }
    http://blog.chinaunix.net/uid-26672038-id-3366869.html
  • 相关阅读:
    mysql服务器上的mysql这个实例中表的介绍
    mysql的innodb存储引擎和myisam存储引擎的区别
    Ubuntu配置java环境变量
    Android_adb shell am/pm使用
    tty相关内容
    Ubuntu和windows共享文件夹
    蓝牙查询网站
    Vim折叠模式设置
    ubuntu下安装jdk
    Linux下Gcc生成和使用静态库和动态库详解
  • 原文地址:https://www.cnblogs.com/yuxinpeng/p/5993659.html
Copyright © 2011-2022 走看看