如何在JavaScript中定义内容 [英] How to define something in JavaScript
问题描述
我知道如何用C ++定义内容。例如:
I know how to define something in C++. For example:
#define ce cout<<"\n";
现在如果我们使用 ce
任何地方它将输出的代码 cout<<\ n;
我正在尝试使用此JavaSvript:
now if we use ce
any where of the code it will output cout<<"\n";
I am trying with this JavaSvript:
#define go document.write
所以,如果我想显示/输出一些东西,我想写一下
So, if i want to show/output something, i wish to write
go('Great!');
现在,这将输出 Great!
in浏览器。但是这个定义
方法无法在JavaScript中运行
now, this will output Great!
in the browser. But this define
method not working in JavaScript
推荐答案
你不能,至少不是C / C ++的方式。但是,您可以为任何变量分配函数:
You can't, at least not the way C/C++ does it. You can however assign a function to any variable:
var go = document.write;
正如所指出的,这不适用于 document.write
因为范围变化。获得具有正确范围的实际函数的一种解决方案是:
As pointed out this won't work for document.write
because of the scope change. One solution to get an actual function with the correct scope would be:
var go = document.write.bind(document);
// Now call
go('Great!');
.bind
的节点不起作用在IE8及更低版本中。
Node that .bind
won't work in IE8 and lower.
这篇关于如何在JavaScript中定义内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!