繁体   English   中英

.bind()对函数不起作用

[英].bind() doesn't work for functions

我正在尝试使用放置在函数内的变量。 我不想对这段代码做任何特别的事情,但是我想弄清楚为什么绑定/应用/调用对对象而不是函数起作用。

function another () {
    this.var = 'another test'
}

function test (){
    this.var = 'test123'
    console.log('this.first: ',this.var);
}

var bind = test.bind(another);
console.log('bind: ', bind());

.bind()对于函数正常工作。 它只是没有按照您的想法去做。

看,函数也是对象。 像对待对象一样对待它们并不意味着它们会被调用。

function a() { console.log("a was called"); }
function b() { console.log(this); }

var bound = b.bind(a);
bound();  // logs "function a() { }" in my console

在你的情况,一旦你势必testanother ,你有作品就像一个新的功能test ,但如果this意味着another ,从而this.var意味着another.var 所有这一切都发生了,而没有another 被称为

我不确定您希望代码如何工作,因为它看起来并不合理。 但是,如果要在运行它之后检查事物,您会发现another.var现在具有值'test123'

即使您事先说过another()也没关系。 首先,因为another不受任何约束,所以对它来说, this意味着全局对象。 在浏览器中, another()基本上只是设置window.var 但是其次, test设置了自己的值-因此,即使两个函数对this.var含义有相同的了解, test也会用'test123'覆盖它。

这将记录“另一个测试”,因为this默认为window

function another() {
    this.foo = 'another test';
}

another();

console.log(window.foo);

编辑:

// define function object window.first:
function first() {
    this.foo = 'first';
}

// define function object window.second:
function second() {
    this.foo = 'second';
}

// call window.first, sets window.foo to 'first':
first();

// set window.bound to a new function object which
// runs second in the context of the object first:
var bound = second.bind(first);

// call window.bound, which sets window.first.foo to 'second':
bound();

// call second, which sets window.foo to 'second' then logs the return
// value of second, which is undefined:
console.log('second: ', second());

暂无
暂无

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

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