Javascript 方法是否可以在回调中不使用bind()引用其对象?
我制作了一个测试用例来展示一个方法在回调中引用其函数时如何需要“bind” 但是就在我以为我知道JS的时候——下面的代码工作得很好——不需要绑定Javascript 方法是否可以在回调中不使用bind()引用其对象?,javascript,oop,bind,Javascript,Oop,Bind,我制作了一个测试用例来展示一个方法在回调中引用其函数时如何需要“bind” 但是就在我以为我知道JS的时候——下面的代码工作得很好——不需要绑定 pretendThingConstructor = function (greeting) { this.greeting = greeting; this.sayHello = function() { console.log(this.greeting); }; } var pretend_thing =
pretendThingConstructor = function (greeting) {
this.greeting = greeting;
this.sayHello = function() {
console.log(this.greeting);
};
}
var pretend_thing = new pretendThingConstructor('hello world');
pretend_thing.sayHello();
setTimeout(function() {
pretend_thing.sayHello()
}, 3000);
当我通过node、phantomjs或其他JS环境运行它时,它就工作了《hello world》印刷两次
我预计第二个“hello world”——在timout之后运行的“hello world”——会失败,因为“this”指的是事件,而不是对象。但它是有效的。为什么会这样?是的,在这种情况下,sayHello的this对象是假装的东西,因为函数知道调用它的是哪个项。只有在您尝试执行此操作时,此功能才会丢失:
var say=假装什么。打招呼;
setTimeout(函数(){
say();//这是窗口或null
}, 15)
//你可以这样做
函数doThings(){
console.log(这个东西);
}
var test1={doThings:doThings,thing:1};
var test2={doThings:doThings,thing:2};
test1.doThings();// 此
根据调用函数的方式而变化。如果指定基础对象,则它将引用该对象:
pretend_thing.sayHello()
这里的假装对象是那个基本对象,因此这个仍然指那个对象。另一方面,如果您有:
var f = pretend_thing.sayHello;
f();
此处此
应参考窗口
对象
您可以通过以下方式进行确认:
console.log (this instanceof pretendThingConstructor);
在sayHello
函数中。在这两种情况下,它都将打印true
将输出:
true
true
鉴于:
var f = pretend_thing.sayHello;
f();
产出:
false
在函数“假装构造函数”的作用域中,“this”指的是函数本身。当构造函数运行时(当您使用'new'关键字实例化一个对象时),sayHello方法(这是一个匿名方法)将被分配给实例化对象上的属性'sayHello'(在您的例子中,是假装的东西)
因为您是从“假装构造函数”对象(假装对象)的实例调用“sayHello”方法,“this”指的是您从中调用方法的对象,而不是您在其中执行的上下文
您可以使用.apply方法更改“this”关键字的含义:
function myHello(){
this.greeting = 'Hello';
this.method = function(){
this.greeting
}
}
function myGoodbye(){
this.greeting = 'Goodbye';
this.say = function(){
console.log( this.greeting );
}
}
var hello = new myHello();
var goodbye = new myGoodbye();
hello.say(); // Outputs 'Hello'
goodbye.say(); // Outputs 'Goodbye'
hello.say.apply( goodbye ); // Outputs 'Goodbye'
false
function myHello(){
this.greeting = 'Hello';
this.method = function(){
this.greeting
}
}
function myGoodbye(){
this.greeting = 'Goodbye';
this.say = function(){
console.log( this.greeting );
}
}
var hello = new myHello();
var goodbye = new myGoodbye();
hello.say(); // Outputs 'Hello'
goodbye.say(); // Outputs 'Goodbye'
hello.say.apply( goodbye ); // Outputs 'Goodbye'