javascript - 对象内部的范围 - this
问题描述
我编写了自己的第一个对象,包括方法,但我并不真正了解其中的范围。我正在编写一个小应用程序,我将不得不一直使用这些鼠标参数。我只想能够通过简单的方式访问这些值
let mouse_positionX = mouse.pos.x;
我的第一次尝试:
function Mouse() {
this.now = { x: 0, y: 0};
this.start = { x: 0, y: 0};
this.stop = { x: 0, y: 0}
this.delta = { x: 0, y: 0};
let getDelta = function(e) {
return { x: (e.clientX - this.start.x), y:(e.clientY - this.start.y) };
}
let move = function(e) {
this.now = { x: e.clientX, y: e.clientY };
this.delta = getDelta(e);
}
let start = function(e) {
document.addEventListener('mousemove', move, false);
this.start = { x: e.clientX, y: e.clientY };
}
let stop = function(e) {
this.stop = { x: e.clientX, y: e.clientY };
this.delta = getDelta(e);
document.removeEventListener('mousemove', move, false);
}
document.addEventListener('mousedown', start, false);
document.addEventListener('mouseup', stop, false);
}
const mouse = new Mouse();
但这不起作用。this
“私有”函数之一的内部指向window
而不是对象本身:
let start = function(e) {
document.addEventListener('mousemove', move, false);
this.start = { x: e.clientX, y: e.clientY };
console.log(this); // window object
}
所以我使用了另一个变量:_self = this
函数之外。_self
比函数内部可用:
function Mouse() {
this.now = { x: 0, y: 0};
this.start = { x: 0, y: 0};
this.stop = { x: 0, y: 0}
this.delta = { x: 0, y: 0};
let _self = this;
let getDelta = function(e) {
return { x: (e.clientX - _self.start.x), y:(e.clientY - _self.start.y) };
}
let move = function(e) {
_self.now = { x: e.clientX, y: e.clientY };
_self.delta = getDelta(e);
}
let start = function(e) {
document.addEventListener('mousemove', move, false);
_self.start = { x: e.clientX, y: e.clientY };
}
let stop = function(e) {
_self.stop = { x: e.clientX, y: e.clientY };
_self.delta = getDelta(e);
document.removeEventListener('mousemove', move, false);
}
document.addEventListener('mousedown', start, false);
document.addEventListener('mouseup', stop, false);
}
const mouse = new Mouse();
我是这种对象用法的新手,所以我有两个问题。我找不到具体的答案,或者我不知道要准确搜索什么。
A:为什么this
里面的一个函数是指向window
对象而不是对象本身?
B:将对象用于这样的事情(并且还绑定到对象内的文档)通常是一个坏主意吗?
解决方案
A:
浏览器中的全局范围总是window
乙:
您不是在使用对象,而是在使用函数。您可以通过在其中创建带有函数的对象来获得很多这种功能。
var Animal = {
type: 'Invertebrates', // Default value of properties
displayType: function() { // Method which will display type of Animal
console.log(this.type);
}
};
var animal1 = Object.create(Animal);
animal1.displayType(); // Output:Invertebrates
var fish = Object.create(Animal);
fish.type = 'Fishes';
fish.displayType(); // Output:Fishes
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
推荐阅读
- javascript - 尝试使用上下文挂钩时使用导入错误
- ios - 如何在 ARFrame 捕获的图像的屏幕上显示文本识别边界框?(iOS)
- python - AttributeError: '' object has no attribute '' - 类内声明的变量无法识别
- pygame - 无法在pygame上移动玩家
- r - 使用 dplyr 从向量列中删除 NA 元素
- reactjs - 如何在 next.js 中添加 axios 拦截器
- javascript - 在API中发布后将项目添加到状态获取ID
- javascript - 如何动态地从输入字段中获取值
- next.js - 缓存已更新,但 UI 在删除突变 NEXTJS SSR 后更新缓存时不会更改
- java - Admob 和 facebook 插页式广告在同一个活动中