在下面的代码我无法理解为什么值this更改为window从document在功能上handler,当我把它从document上下文.
$(document).ready(function() {
var handler = function() {
console.log(this); // this = window
}
console.log(this); // this = document
handler();
})
Run Code Online (Sandbox Code Playgroud)
根据我的理解,价值this取决于其执行背景.现在当我是预期的document.ready功能this点document时,但是当我从该上下文调用方法时,为什么我的上下文会window从中变为document.
提前致谢.
我找到了这个示例代码:
function personFullName() {
return this.first + ' ' + this.last;
}
function Person(first, last) {
this.first = first;
this.last = last;
this.fullName = personFullName;
}
var dude = new Person("Michael", "Jackson");
alert(dude.fullName());
Run Code Online (Sandbox Code Playgroud)
哪个警告"迈克尔杰克逊".我将其更改为personFullName从构造函数调用而不是分配函数对象:
function personFullName() {
return this.first + ' ' + this.last;
}
function Person(first, last) {
this.first = first;
this.last = last;
this.fullName = personFullName();
}
var dude = new Person("Michael", "Jackson");
alert(dude.fullName);
Run Code Online (Sandbox Code Playgroud)
我希望"fullName"属性现在是一个字符串而不是一个函数.但现在它警告"undefined undefined".任何人都可以解释为什么我的版本不起作用?
从异步方法调用时如何引用类实例。
class Senders {
callSendAPI() {
//Some code here
}
sendText() {
this.callSendAPI();
}
async sendCards() {
var dbpromise = await db.call();
console.log('this= ', this);
this.callSendAPI();
}
}
export {Senders};
Run Code Online (Sandbox Code Playgroud)
这=未定义
我必须弄明白,如何以正确的方式开发oop-javascript.我读了很多,prototypes但互联网向我解释,我只需要它,如果我多次创建一个对象.但我SuperInterface只存在一次.所以我把它创建为一个对象:
var SuperInterface = {
superaction: function () {
alert(1);
},
actions: [{
title: 'This is great',
do_this: this.superaction
}],
init: function () {
console.log(this.actions[0].title);
this.actions[0].do_this();
}
};
SuperInterface.init();
Run Code Online (Sandbox Code Playgroud)
运行init()将title成功放入控制台.但是警报从未被调用过.我不明白,为什么不呢?我应该改变什么?
我以为我知道JavaScript,似乎我不知道.
我想定义一个像这样的对象.(例如http://www.phpied.com/3-ways-to-define-a-javascript-class/)
var apple = {
type: "macintosh",
color: "red",
getInfo: function () {
return this.color + ' ' + this.type + ' apple';
}
}
Run Code Online (Sandbox Code Playgroud)
好吧,这看起来很好,让我们打印信息......
apple.getInfo() //returns "red macintosh apple" as expected
Run Code Online (Sandbox Code Playgroud)
好了,现在把功能拿出来再运行一次......
var func = apple.getInfo; func(); //returns "undefined undefined apple"
Run Code Online (Sandbox Code Playgroud)
嗯,这不是我的预期.显然,this被解释为window.这不是我想要的.
我的问题是 - 什么是重写apple文字的惯用的首选方法,以便apple.getInfo返回一个可以单独运行但仍然使用对象属性的函数?