• JS 中 new 操作符


    按照javascript语言精粹中所说,如果在一个函数前面带上new来调用该函数,那么将创建一个隐藏连接到该函数的prototype成员的新对象,同时this将被绑定到那个新对象上。这个话很抽象,我想用实例来让自己加深理解。

    1.如果就一个函数,没有返回值,没有prototype成员,然后使用new,会是什么结果呢?如果一个函数没有返回值,那么如果不使用new来创建变量,那么该变量的值为undefined.如果用了new,那么就是Object.说明一个函数的默认的Prototype是Object.

    复制代码
    function Test1(str) {
    this.a = str;
    }
    var myTest = new Test1("test1");
    alert(myTest); //[object Object]
    function Test1WithoutNew(str) {
    this.a = str;
    }
    var myTestWithoutNew = Test1WithoutNew("test1");
    alert(myTestWithoutNew); //undefined;
    复制代码

    2.如果函数有返回值,但是返回值是基本类型。那么new出来的myTest还是object.因为基本类型的prototype还是Object. 而如果不使用new,那么返回值就是string的值。

    复制代码
    function Test1(str) {
    this.a = str;
    return this.a;
    }
    var myTest = new Test1("test1");
    alert(myTest); //Object

    function Test1WithoutNew(str) {
    this.a = str;
    return this.a;
    }
    var myTestWithoutNew = Test1WithoutNew("test1");
    alert(myTestWithoutNew); //"test1"
    复制代码

    3。如果函数的返回值为new出来的对象,那么myTest的值根据new出来的对象的prototype而定。

    function Test1(str) {
    this.a = str;
    return new String(this.a);
    }
    var myTest = new Test1("test1");
    alert(myTest); //String "test1"

    4。接下来我们开始讨论new中的this。如果我们给Test1的prototype中加入一个方法叫get_string(),那么get_string()中的this指的就是这个新对象。能够得到在new时候赋予该对象的属性值。

    复制代码
    var Test2 = function(str) {
    this.a = str;
    }

    Test2.prototype.get_string = function () {
    return this.a;
    };

    var myTest2 = new Test2("test2");
    alert(myTest2.get_string()); //“test2”

    var Test2 = function(str) {
    this.a = str;
    }

    Test2.prototype.get_string = function () {
    return this.a;
    };

    var myTest2 = Test2("test2");
    alert(myTest2)//undefined
    复制代码

    5。如果我们修改了函数的prototype,又会发生什么样的情况呢? 那么就会发生类似继承的功能,其实就是js的伪类实现。

    复制代码
    function Test1(str) {
    this.b = str;
    }
    Test1.prototype.Get_Test1String = function () {
    return this.b;
    };

    var Test2 = function(str) {
    this.a = str;
    }
    Test2.prototype = new Test1("test1");
    Test2.prototype.get_string = function () {
    return this.a;
    };

    var myTest2 = new Test2("test2");
    alert(myTest2); //Object
    alert(myTest2.get_string()); //"test2"
    alert(myTest2.Get_Test1String()); //"test1"
    复制代码
     
    转载 http://www.cnblogs.com/RitaRichard/archive/2011/10/12/2208902.html
  • 相关阅读:
    对搜狗浏览器的评价
    领扣(LeetCode)二叉树的所有路径 个人题解
    领扣(LeetCode)单词模式 个人题解
    领扣(LeetCode)最长公共前缀 个人题解
    领扣(LeetCode)设计哈希映射 个人题解
    领扣(LeetCode)寻找旋转排序数组中的最小值 个人题解
    领扣(LeetCode)最长和谐子序列 个人题解
    领扣(LeetCode)删除注释 个人题解
    领扣(LeetCode)检测大写字母 个人题解
    领扣(LeetCode)第三大的数 个人题解
  • 原文地址:https://www.cnblogs.com/lsc-boke/p/6051319.html
Copyright © 2020-2023  润新知