为什么我自己的 "toString()" 函数在我的 javascript 中不起作用?
Why my own "toString()" function doesn't work in my javascript?
我在 chrome 调试控制台中尝试过:
>function m(){function toString(){return "abc"}}
undefined
>new m().toString()
"[object Object]"
我希望它打印 "abc"。为什么?
您没有使用自己的 toString
方法(这是 m
中的私有函数),而是来自 Object
.
的方法
对于您自己的方法,您需要将您的 toString
方法分配给 m
的原型,例如
m.prototype.toString = function () { return 'abc'; };
function m() {}
m.prototype.toString = function () { return 'abc'; };
console.log((new m).toString());
试试这个。
function m() {
this.toString = function() {
return "abc";
}
}
var m1 = new m();
alert(m1.toString());
您的代码有误。您可以尝试此代码并在此处检查输出 http://jsbin.com/luremulano/edit?html,js,console,output
console.log(m('abc'));
function m(a){
return a.toString();
}
我在 chrome 调试控制台中尝试过:
>function m(){function toString(){return "abc"}}
undefined
>new m().toString()
"[object Object]"
我希望它打印 "abc"。为什么?
您没有使用自己的 toString
方法(这是 m
中的私有函数),而是来自 Object
.
对于您自己的方法,您需要将您的 toString
方法分配给 m
的原型,例如
m.prototype.toString = function () { return 'abc'; };
function m() {}
m.prototype.toString = function () { return 'abc'; };
console.log((new m).toString());
试试这个。
function m() {
this.toString = function() {
return "abc";
}
}
var m1 = new m();
alert(m1.toString());
您的代码有误。您可以尝试此代码并在此处检查输出 http://jsbin.com/luremulano/edit?html,js,console,output
console.log(m('abc'));
function m(a){
return a.toString();
}