qq_花開(kāi)花謝_0
2023-05-25 16:11:39
我編寫(xiě)了自己的第一個(gè)對(duì)象,包括方法,但我并不真正理解其中的作用域。我正在編寫(xiě)一個(gè)小應(yīng)用程序,我將不得不一直使用這些鼠標(biāo)參數(shù)。我只想能夠通過(guò)簡(jiǎn)單的方式訪問(wèn)這些值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其中一個(gè)“私有”函數(shù)的內(nèi)部指向window對(duì)象本身而不是對(duì)象本身:let start = function(e) { document.addEventListener('mousemove', move, false); this.start = { x: e.clientX, y: e.clientY }; console.log(this); // window object }所以我使用了另一個(gè)變量:_self = this在函數(shù)之外。_self在函數(shù)內(nèi)部可用: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 }; }我對(duì)這種對(duì)象用法不熟悉,所以我有兩個(gè)問(wèn)題。我找不到具體的答案,或者我不知道要搜索什么。A:為什么this里面的一個(gè)函數(shù)是指向window對(duì)象而不是對(duì)象本身?B:為這樣的事情使用對(duì)象通常是個(gè)壞主意(并且還綁定到對(duì)象內(nèi)部的文檔)嗎?
1 回答

鴻蒙傳說(shuō)
TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
A:
瀏覽器中的全局范圍始終是window
乙:
您不是在使用對(duì)象,而是在使用函數(shù)。您可以通過(guò)在其中創(chuàng)建帶有函數(shù)的對(duì)象來(lái)獲得很多這種功能。
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
添加回答
舉報(bào)
0/150
提交
取消