我可以像任何其他对象一样扩展未定义的对象吗? [英] Can I extend the undefined object like any other object?
问题描述
我想为 String
对象创建一个方法,检查它是否未定义:
I want to create a method for the String
object that checks if it's undefined:
String.prototype.isDefined = (str) => typeof str === 'undefined';
虽然,如果字符串未定义,我无法使用此方法或JavaScript将中断(和它也永远是真的)。我想知道我是否可以以类似的方式扩展未定义的对象。我试过了:
Although, if the string is undefined I can't use this method or the JavaScript will break (and also it will always be true). I wonder if I can extend the undefined object in a similar fashion. I tried:
undefined.prototype.isDefined = () => false;
但它似乎不起作用。
我知道我可以写一个函数,但目的是更清晰,更易读的代码。
I know I could write a function, but the purpose is cleaner, more easily readable code.
推荐答案
不,你不能。 undefined
不是一个对象,它是一个值。
No, you can't. undefined
is not an object, it's a value.
你不可能编写一个函数来检查是否字符串未定义。如果它未定义,则不是字符串。这是未定义的。
You can't possibly write a function that checks if a string is undefined. If it's undefined, it's not a string. It's undefined.
我看不到什么是不干净或可读的
I don't see what is not clean or readable with
function isDefined(x) { return x !== undefined; }
这篇关于我可以像任何其他对象一样扩展未定义的对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!