function m(){function toString(){return "abc"}} undefined >new m().toString()-6ren">
gpt4 book ai didi

javascript - 为什么我自己的 "toString()"函数在我的 javascript 中不起作用?

转载 作者:行者123 更新时间:2023-11-29 16:06:54 25 4
gpt4 key购买 nike

我在我的 chrome 调试控制台中试过:

>function m(){function toString(){return "abc"}}
undefined
>new m().toString()
"[object Object]"

我希望它打印“abc”。为什么?

最佳答案

您没有使用自己的toString 方法(它是m 中的私有(private)函数),而是来自Object 的方法。 .

对于您自己的方法,您需要将您的toString 方法分配给m 的原型(prototype),例如

m.prototype.toString = function () { return 'abc'; };

function m() {}
m.prototype.toString = function () { return 'abc'; };

console.log((new m).toString());

关于javascript - 为什么我自己的 "toString()"函数在我的 javascript 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39265423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com