Last active
October 27, 2017 06:41
-
-
Save mygoare/f8a034af69e9ae2d82f521f91a4c8746 to your computer and use it in GitHub Desktop.
javascript new 操作符
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
总的来说,理解了下面这句话,对于下面的例子就很好理解了,都是为了加深理解而举得下面的例子。 | |
按照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" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment