Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Class self bindings not preserved through destructuring of methods #2068

Open
Agapurnis opened this issue Jul 29, 2022 · 2 comments
Open

Class self bindings not preserved through destructuring of methods #2068

Agapurnis opened this issue Jul 29, 2022 · 2 comments

Comments

@Agapurnis
Copy link

Agapurnis commented Jul 29, 2022

Alternatively: Destructing a class method causes it to lose it's sense of self ;)

I'm not entirely sure how one would go about fixing this, but I'd figure I may as well report it instead of letting it go undocumented.

One potential way might be to simply pass the _binding with all invocations.

-- ...
local _binding = messenger
local sayHi = _binding.sayHi
sayHi(_binding)
-- ...

Or treat it as an alias during compilation, not creating a separate variable.


Input:

class Messenger {
	message = "Hello, world!";

	sayHi () {
		print(this.message);
	}
}

const messenger = new Messenger();

messenger.sayHi(); // This works fine.

const { sayHi } = messenger;

sayHi(); // Issue arises here.

A more realistic case where one might encounter would likely involve destructuring in callback parameters, which is where I found encountered this issue.

Output:

-- Compiled with roblox-ts v1.3.3
local Messenger
do
	Messenger = setmetatable({}, {
		__tostring = function()
			return "Messenger"
		end,
	})
	Messenger.__index = Messenger
	function Messenger.new(...)
		local self = setmetatable({}, Messenger)
		return self:constructor(...) or self
	end
	function Messenger:constructor()
		self.message = "Hello, world!"
	end
	function Messenger:sayHi()
		print(self.message)
	end
end
local messenger = Messenger.new()
messenger:sayHi()
local _binding = messenger
local sayHi = _binding.sayHi
sayHi()
return nil

Error:

8: attempt to index nil with 'message'
@Dionysusnu
Copy link
Contributor

Dionysusnu commented Jul 29, 2022

Pretty sure I've already got this fixed in a PR - or maybe even merged into master already.

Yes, fixed by #1888 which is already merged. That should work with classes too, but I'll double check later just to make sure.

@Validark
Copy link

Validark commented Aug 11, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants