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

super in private method #2039

Closed
morten-krogh opened this issue Feb 21, 2022 · 2 comments
Closed

super in private method #2039

morten-krogh opened this issue Feb 21, 2022 · 2 comments

Comments

@morten-krogh
Copy link

morten-krogh commented Feb 21, 2022

The following example contains a call to a super class method in a base class using the keyword super.

class B {
	getValue() {
		return 5;
	}
}

class D extends B {

	pub() {
		return this.#priv();
	}

	#priv() {
		return super.getValue();
	}
}

const d = new D();
const value = d.pub();
console.log('value =', value);

Building this to targets, like es2016, without private methods lead to a free standing function with the super keyword.

var __accessCheck = (obj, member, msg) => {
  if (!member.has(obj))
    throw TypeError("Cannot " + msg);
};
var __privateAdd = (obj, member, value2) => {
  if (member.has(obj))
    throw TypeError("Cannot add the same private member more than once");
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value2);
};
var __privateMethod = (obj, member, method) => {
  __accessCheck(obj, member, "access private method");
  return method;
};
var _priv, priv_fn;
class B {
  getValue() {
    return 5;
  }
}
class D extends B {
  constructor() {
    super(...arguments);
    __privateAdd(this, _priv);
  }
  pub() {
    return __privateMethod(this, _priv, priv_fn).call(this);
  }
}
_priv = new WeakSet();
priv_fn = function() {
  return super.getValue();
};

This output is not valid javascript.

@hyrious
Copy link

hyrious commented Feb 21, 2022

Note that tsc does the same:
Playground Link

class A extends Error {
  #f() { return super.g(); }
}

becomes

var _A_instances, _A_f;
class A extends Error {
    constructor() {
        super(...arguments);
        _A_instances.add(this);
    }
}
_A_instances = new WeakSet(), _A_f = function _A_f() { return super.g(); };

@evanw
Copy link
Owner

evanw commented Mar 1, 2022

I believe the relevant TypeScript issue is this one: microsoft/TypeScript#44515

@evanw evanw closed this as completed in 0a7ac6f Apr 5, 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