JavaScript保存document.write在变量中并调用它

JavaScript保存document.write在变量中并调用它,javascript,Javascript,我正在尝试传递文档。将作为变量的引用写入: 例如: var f = document.write //then f('test'); 它与警报一起工作。为什么它不适用于文档。write?一些函数,包括eval和文档。write不能间接使用(即通过变量引用) 如果仍要使用文档。使用f编写,请使用: function f(s){ document.write(s); } f('test'); 为什么它不起作用我不能说没有更多的研究,但要解决你的问题: var f = function(

我正在尝试传递
文档。将
作为变量的引用写入:

例如:

var f = document.write

//then
f('test');

它与警报一起工作。为什么它不适用于
文档。write

一些函数,包括
eval
文档。write
不能间接使用(即通过变量引用)

如果仍要使用
文档。使用
f
编写
,请使用:

function f(s){
    document.write(s);
}
f('test');

为什么它不起作用我不能说没有更多的研究,但要解决你的问题:

var f = function(i) { document.write(i); }

因为
alert
不关心这个
是什么(
alert
是全局的),而
document.write
关心(它需要知道它正在向哪个文档写入)

如果您想要一个包装器,那么就编写一个快捷方式函数

function f(str) { document.write(str); }

…然后按照惯例为调用变量
f
而将自己取出内脏。是好代码的一个优点。

因为它在
write
函数中丢失了
this
的正确值

您可以传递对
文档的引用

var f = document;

f.write("hello");

或者像其他解决方案建议的那样包装它。

我想这是因为您没有将f应用于文档(而是应用于窗口)

这项工作:

var f = document.write;
f.call(document, "Hello world!!!");

另一种奇怪的方法是:

var f = window.document.write;
f.call(window.document, "test")
或:


除了已经说过的,JavaScript1.8.5还有一个本机解决方案:


上面的链接还包含不支持JS1.8.5的浏览器的仿真代码

与此问题中发布的问题相同:

正如其他人提到的,您正在失去函数上下文。函数是javascript中的对象。通过调用
var f=document.write
可以获得对函数的引用,但函数没有对它所需文档的引用

例如:

// give the window a new funciton
window.foo = function () {
    console.log('FOO!);
}

// get a reference to this funciton
var fn = window.foo;

// call via reference works and outputs 'FOO!!' to the console
fn();

// attach it to your object
var myObject = {};
myObject.Foo = fn;

// call it it still works
myObject.Foo();
现在,如果函数引用了
this
,则上述操作不起作用,因为
this
依赖于调用上下文。目前保存上下文的方法是使用这样的闭包

// remember this is the window context

var fn = function (s) { 
    document.write(s);
}

上面代码工作的原因是javascript查看函数,没有看到本地
文档
对象,因此它沿着作用域走过去,看到外部作用域(在本例中,
窗口
对象)有一个文档,并在其上调用write。实际上,对
document.write()
的调用与写入
window.document.write()

可能不起作用,因为
write
函数希望在
文档的上下文中执行,而不是在
窗口中执行。您可以
.bind()
它,但对于较旧的浏览器,您需要一个垫片,我不知道这会对性能产生什么影响
var f=document.write.bind(文档)
@Dennis
文档。当函数被间接引用时,write
似乎失去了上下文。使用该方法时,可以间接引用
文档。编写
。代码:var f=document.write;f、 调用(document,'test')
如果您想通过变量引用它,您必须引用一个函数,即:
var f=function(i){document.write(i);}
关于
eval
,您是在讨论特定的浏览器问题吗?ES-5描述了对
eval
的间接调用所需的行为,并引用了ES-3下的间接调用行为……啊,我看到一定有具体的实现问题:“不再允许实现以非直接调用的方式限制eval的使用。”确切地说,您必须这样调用
f
f.apply(document,[str])
。。。我想这有点违背目的吧?至少您仍然可以创建对
文档
对象的缩短引用。
// give the window a new funciton
window.foo = function () {
    console.log('FOO!);
}

// get a reference to this funciton
var fn = window.foo;

// call via reference works and outputs 'FOO!!' to the console
fn();

// attach it to your object
var myObject = {};
myObject.Foo = fn;

// call it it still works
myObject.Foo();
// remember this is the window context

var fn = function (s) { 
    document.write(s);
}