JS 中 new 操作符

来源:互联网 发布:营销网络的含义 编辑:程序博客网 时间:2024/04/28 03:54

按照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); //Objectfunction 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); //Objectalert(myTest2.get_string()); //"test2"alert(myTest2.Get_Test1String()); //"test1"
原创粉丝点击