亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

對象內部的作用域 - 這個

對象內部的作用域 - 這個

qq_花開花謝_0 2023-05-25 16:11:39
我編寫了自己的第一個對象,包括方法,但我并不真正理解其中的作用域。我正在編寫一個小應用程序,我將不得不一直使用這些鼠標參數。我只想能夠通過簡單的方式訪問這些值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 };  }我對這種對象用法不熟悉,所以我有兩個問題。我找不到具體的答案,或者我不知道要搜索什么。A:為什么this里面的一個函數是指向window對象而不是對象本身?B:為這樣的事情使用對象通常是個壞主意(并且還綁定到對象內部的文檔)嗎?
查看完整描述

1 回答

?
鴻蒙傳說

TA貢獻1865條經驗 獲得超7個贊

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

查看完整回答
反對 回復 2023-05-25
  • 1 回答
  • 0 關注
  • 138 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號