如何制作“点功能”在JavaScript中 [英] How to make a "dot function" in javascript

查看:97
本文介绍了如何制作“点功能”在JavaScript中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在没有参数的情况下定义一个点函数,但它有一个以及之前的字符串或数字:

I'm trying to define a "dot function" where there are no parameters but has a . and a string or number before it like these:


.toUpperCase()

.toLowerCase()
$ b $ .indexOf()

.charAt()

.substring()

.toUpperCase()
.toLowerCase()
.indexOf()
.charAt()
.substring()

您可以做 2..toString ,而不是 toString(2)

你如何定义其中之一?

为什么当我输入 4..toString()时,它会返回 function toString(){[native code]}

And why when I type 4..toString() it returns function toString() {[native code]}?

推荐答案

简单。

var a = {}, or a = function() {}, or a = [], etc.

a.dotFunction = function() { return 'hi'; }

console.log(a.dotFunction());

如果要在类的所有实例上定义它,请使用原型

If you want to define it on all instances of a "class", use prototype.

function someClass() {
}

someClass.prototype.dotFunction = function() { return 'hi'; };

console.log(new someClass().dotFunction());

甚至可以在内置类型上执行此操作(有些类似Prototype.js,虽然大多数人推荐它)。

You can even do this on built-in types (some, like Prototype.js, do this, though most recommended against it).

Number.prototype.dotFunction = function() { return 'hi'; };

console.log((0).dotFunction()); 

这篇关于如何制作“点功能”在JavaScript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆