javascript tostring自动调用,javascripttostring
分享于 点击 25098 次 点评:164
javascript tostring自动调用,javascripttostring
1.最近tostring频频出现在视野中,jquery源码里面有看到,朋友的面试题里面有,好吧,那就去一探究竟。
这是面试 题:
function add(x) {________}; alert(add(2)(3)(4)); //填空,使结果为9
这是网友给的答案,感谢万能的群,感谢万能的网友
function fn(x) {
var b = x;
function help(a) {
b += a
console.log("help")
return help
}
help.toString = function() {
console.log("help==tostring")
return b;
}
console.log("第一次?")
return help;
}
//console.log(fn(1).toString()) //help tostring 只打印一次
alert(fn(1))//help tostring 2次
这里可以看到toString被改下了,这样就可以实现连续()!!!!!!!黑魔法?震惊WOW。从业三年进入不知道JAVASCRIPT还有这个姿势。
百度~~ 必应~~google~~~~~~~~~之后
司徒的博客:http://www.cnblogs.com/rubylouvre/archive/2012/02/15/2351991.html
2012年,别人就已经知道了,/(ㄒoㄒ)/~~,有点打击~~~~
继续:
function ulbuilder() {
var lis = '';
this.addli = function(litext) {
lis += '<li>' + litext + '</li>';
};
this.toString = function() {
console.log("呵呵呵")
return '<ul>' + lis + '</ul>';
};
}
var ulhtml = new ulbuilder();
ulhtml.addli('javascript事件冒泡应用实例');
ulhtml.addli('执行ajax返回html片段中的javascript脚本');
var a=ulhtml;
alert(a);
console.log(a+"1000000")
toString在调用ulhtml的时候会直接运行~~~,可以得到:对象调用的时候会自动运行底层toString方法~~
这里有个坑,如果直接console.log(a),返回的是该对象本身,不明白原因
为了验证上面的结论再来一个例子:
var userinfo = {
"name": "mike",
"age": 23,
"phone": "020-87654321",
"toString": function() {
var objstr = '';
for (var key in this) {
if (typeof(this[key]) == 'string')
objstr += '"' + key + '":"' + this[key] + '",';
}
return '{' + objstr.replace(/,$/, '') + '}';
}
}
alert(userinfo);
这个代码会自动过滤掉非string类型的元素,证实toString的确可以自动运行,通过改写它可以带来一些遍历[切记不要改写原生对象的toString]
补充一个例子:
直接调用对象的时候才会触发toString,如果直接返回y的话无效的
function a(x){
var y=100;
a.toString=function(){
return x+y;
}
return a;
}
alert(a(10))
这里有涉及一个问题,ValueOf和toString的优先级和区别:
可以参考:
http://www.jb51.net/article/32327.htm
本篇代码来源:
http://www.makaidong.com/JavaScript/103972.shtml
提供参考:
http://www.cnblogs.com/zhangdongming/p/5361569.html
http://blog.csdn.net/txl910514/article/details/52490969
相关文章
- 暂无相关文章
用户点评