简体   繁体   English

在javascript中定义内置类型的方法

[英]define method on built-in type in javascript

Problem for example: In general null object means additional class which handle cases when object not found etc. In Ruby you can also define method for Nil class. 例如的问题:通常, null object意味着附加类,该类处理未找到对象时的情况等。在Ruby中,您还可以为Nil类定义方法。 And I want realise something similiar in js. 我想在js中实现类似功能。

That's what gives me hope typeof(null) //=> object , but in same time null instanceof Object //=> false . 那就是给我希望的typeof(null) //=> object ,但是与此同时null instanceof Object //=> false So defining method for Object gives me nothing. 因此,为Object定义方法没有任何帮助。

So the final question: is there any hacks to define method on built-in types? 因此,最后一个问题是:是否有一些技巧可以在内置类型上定义方法?

Please don't. 请不要

That's really bad form and will lead to nasty, hard to find, bugs. 那真的是不好的形式,并且会导致令人讨厌,难以发现的错误。

Or if you do - do it with greatest of cares . 或者,如果您愿意,则应格外小心

Read here for more: http://perfectionkills.com/extending-built-in-native-objects-evil-or-not/ 在这里阅读更多信息: http : //perfectionkills.com/extending-built-in-native-objects-evil-or-not/

You can do that in javascript too. 您也可以在javascript中执行此操作。

I am not sure whether I understand your question.But here is my take on it. 我不确定我是否理解你的问题。但这是我的看法。

alert(typeof(null));//gives you object.

MyObject=Object.create(null);

This means 这意味着

  1. MyObject doesn't inherit from anywhere MyObject不会从任何地方继承

  2. MyObject has no properties at all. MyObject完全没有属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM