JS constructor
Javascript确实是很烦人, 但也很诱人
这次记录constructor, 与之相关的, 还有typeof, ==, ===
试测测以下代码的结果
function demo(){
var str1="abc";
var str2=new String("abc");
var str3=new Array("abc");
alert(typeof str1);
alert(typeof str2);
alert(typeof str3);
alert(str1.constructor);
alert(str2.constructor);
alert(str3.constructor);
alert(str1 instanceof String);
alert(str2 instanceof String);
alert(str3 instanceof Array);
alert(str1==str2);
alert(str1==str3);
alert(str2==str3);
alert(str1===str2);
alert(str1===str3);
alert(str2===str3);
}
结果为
string
object
object
function String(){...}
function String(){...}
function Array(){...}
false //*1, string比较麻烦
true
true
true
true
false //*2, 2个实例进行==运算, 肯定false, 哪怕重写prototype valueOf()和toString()
false
false
false
*1, string在JS里很麻烦, 介于基本类型和对象之间, typeof "abc" -> string
"abc".constructor也是function String(){...}
但, "abc" instanceof String 却又是false, 在没有进一步了解之前, 权当是历史遗留问题吧
*2, ==运行, 对象跟string(非String)时, 会先调用对象的valueOf取值, 如果没有valueOf, 则调用toString, 然后跟string对比, 但Date对象是先toString, 然后才是valueOf
实例验证
- function demo(){
- var A=function(n){
- this.name=n;
- }
- A.prototype.valueOf=function(){return this.name;}
- A.prototype.toString=function(){return "A: "+this.name;}
- var B=function(n){
- this.name=n;
- }
- B.prototype.valueOf=function(){return this.name;}
- B.prototype.toString=function(){return "B: "+this.name;}
- var c="david";
- var a=new A("david");
- var b=new B(c);
- alert(c==a);
- alert(c==b);
- alert(a==b);
- }
结果:
true
true
false
看见上面的结果了吧, 有够烦人的
下面还有, 但好理解一点, 关于继承的
- function demo(){
- var A=function(name){
- this.name=name;
- }
- A.prototype.showName=function(){alert(this.name);} //the function return this, "this" is the pointer of instance
- A.prototype.showSex=function(){alert("male");}
- A.prototype.city="shenzhen";
- var B=function(name, age){
- A.call(this, name);
- this.age=age;
- }
- B.prototype=A.prototype;
- B.prototype.showAge=function(){alert(this.age);}
- var b=new B("david", 31);
- try {
- alert(b.constructor); //*1
- alert(b.constructor==A); //*2
- alert(b.constructor==B); //*3
- alert(b instanceof A); //*4
- alert(b instanceof B); //*5
- } catch (exception) {
- alert(exception);
- }
- }
结果是
1:function A{this.name=name;}
2:true
3:false //构造器指针指向A
4:true
5:true