How to get the method name of a getter on JavaScrpt? [duplicate] - javascript

This question already has answers here:
Is it possible to get a reference to the setter function of a "setter"?
(2 answers)
Closed 18 days ago.
Is there any way to get programatically the name of a getter method on Javascript?
For example:
class Example {
methodA() {}
get methodB() {}
}
console.log('works', Example.prototype.methodA.name);
console.log('fails', Example.prototype.methodB.name);
I want to do that because I am using a Proxy to handle an extension of a class and want to detect when the getter method is called.
Sure I can use:
if (prop === 'methodB')
But then, case the method is renamed I/anyone else will have to remember to rename the if checks. Example.prototype.methodA.name is always updated.

You can get the name of the method by using :
Object.getOwnPropertyDescriptor(obj, prop).get.name
Example:
class Example {
methodA() {}
get methodB() {}
}
const methodBGetter = Object.getOwnPropertyDescriptor(Example.prototype, 'methodB').get;
console.log(methodBGetter.name);
console.log will be "get methodB".

Related

Differentiate between object property call and get [duplicate]

This question already has answers here:
Add a return type of string when a function is accessed like a variable
(2 answers)
Passing Argument to JavaScript Object Getter
(3 answers)
JavaScript - Variable/object as string and function at the same time
(1 answer)
Closed 23 days ago.
Assume we have the following object
const foo = {
bar: "hello "
}
Is it possible to achieve the following result:
console.log(foo.bar) // logs "hello "
console.log(foo.bar("world")) // logs "hello world"
I want to be able to get or call the same property and apply a function if called
I have tried using Proxy https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy with apply() handler, however I was not able to find a working solution, every attempt ends at This expression is not callable. Type 'String' has no call signatures.

.bind not working with es6 class instance [duplicate]

This question already has answers here:
Can you bind 'this' in an arrow function?
(14 answers)
Closed 2 years ago.
using the bind documentation, if i replace the object (defined as module in their example), with an es6 class instance, it does not bind.
here are the docs...
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind
and here is my code...
class Foo {}
let foo = new Foo()
let fooVar = 'foo var'
let fooFunc = () => {
return this.var
}
foo['var'] = fooVar
fooFunc.bind(foo)
foo['func'] = fooFunc
// i expected this to return 'foo var', but instead get 'undefined'
foo.func()
how can i essentially add an instance method to an existing instance, and have it bind properly?
If you read the documentation about arrow function you will see that:
Does not have its own bindings to this or super, and should not be used as methods.
Therefore you cant bind a new this if it doesnt have one

What is the syntax for private method in browser Javascript class(not node.js)? [duplicate]

This question already has answers here:
Private properties in JavaScript ES6 classes
(41 answers)
Closed 4 years ago.
I know this question has been asked for many times, however, most of them are either for the Node.js solutions or does not work in the browsers.
So, is it possible to implement a private method in browser javascript class?
<html>
<body>
<script>
class Happy
{
constructor()
{
}
_leo()
{
console.log("ff");
}
}
var h=new Happy();
h._leo();
</script>
</body>
</html>
However, the above code still outputs "ff" in the console, how can I fix it?
This illustrates how to hide a method name, effectively making the method uncallable outside the hiding closure:
const Klass = (function() {
const privName = Symbol("priv");
class Klass {
publ() {
console.log("in publ");
this[privName]();
}
[privName]() {
console.log("in priv");
}
}
return Klass;
})()
let inst = new Klass();
inst.publ();
// => in publ
// in priv
It uses the fact that Symbol() returns an entity that cannot be replicated, the fact that privName is not exposed anywhere outside the closure, and the fact that we can define properties with calculated names using the square bracket notation.
Unlike the function-hiding mechanism demonstrated by ultratoad, this is not just a helper function, it is a true method. Just note that you can't call it using the dot notation - dot notation only works when you know the name, and here, no-one does except privName.

How to destructure an object into parameter names [duplicate]

This question already has answers here:
Is there a way to provide named parameters in a function call in JavaScript?
(12 answers)
How to get function parameter names/values dynamically?
(34 answers)
Closed 4 years ago.
I have many functions defined elsewhere that look like this
export function foo(bar1, bar2, bar3, ...) {
// does stuff
}
In the module I am working on I am passed both the function above and an object containing the parameters like this:
// params = {
// bar1: bar1Value,
// bar2: bar2Value,
// bar3: bar3Value,
// ...
// }
function myFunc(foo, params) {
}
I need to call func with the params in the correct order. It is an object not an array so I can't rely on the property order, I need to match up the params to the signature of the function. Is this possible?
Edit to add: There are hundreds of functions that can be passed in, I am trying to avoid refactoring them all, but it seems that it is impossible to look up the parameter names directly. However I've found this which shows it can be done by breaking down the function as a string.
You can access the properties of an object (like "params") either like
params.bar1 or like params["bar1"] and you can get the names of the properties by using Object.keys(params), if thats what your asking for.
See also https://www.w3schools.com/js/js_object_properties.asp and https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

How to call JavaScript class's method from another method? [duplicate]

This question already has answers here:
'this' keyword overriden in JavaScript class when handling jQuery events
(2 answers)
es6 classes and "this" with event handlers [duplicate]
(2 answers)
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
I am using iOS's JavaScriptCore framework but I am having difficulty getting a JavaScript (es6) class to call another method. Here is my playground code.
do {
let j = JSContext()!
j.evaluateScript("class Base123 { method1(arg1) { return this.method2(arg1) } method2(arg1) { return {\"asdf\":\"123\"} } }")
j.evaluateScript("var b = new Base123(); var handler = b.method1")
j.evaluateScript("handler(4)")?.toDictionary() //<-- expected ["asdf": "123"]
}
Essentially I am Creating a class called Base123 with two methods. method1 calls method2. However the call to method2 is undefined.
Does anyone know how to do this?
Reformatting the class definition to make it easier to read:
class Base123 {
method1(arg1) {
return this.method2(arg1)
}
method2(arg1) {
return {"asdf":"123"}
}
}
Is there something wrong with this javascript definition?
Try replacing var handler = b.method1 with var handler = b.method1.bind(b).

Categories

Resources