首页 > 解决方案 > 对象内部的范围 - 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:将对象用于这样的事情(并且还绑定到对象内的文档)通常是一个坏主意吗?

标签: javascriptoopobjectscopethis

解决方案


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


推荐阅读