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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值