我編寫了自己的第一個對象,包括方法,但我并不真正理解其中的作用域。我正在編寫一個小應用程序,我將不得不一直使用這些鼠標參數。我只想能夠通過簡單的方式訪問這些值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:為這樣的事情使用對象通常是個壞主意(并且還綁定到對象內部的文檔)嗎?
對象內部的作用域 - 這個
qq_花開花謝_0
2023-05-25 16:11:39