Adding Custom Properties to a Function

Adding custom properties to a function

It's a little bit difficult to give a very meaningful answer to your question, because you've sort of said "Here is my solution, is it OK?" without explaining what problem you are trying to solve (you even said explicitly that you are not going to explain the "why"). Your code looks to be valid JavaScript that will run, but it also looks like a less than optimal way of doing things.

If you explain what you actually want to achieve you may get some good suggestions on better ways to structure your code. Still, I'll give you some kind of answer:

Can this method be considered "proper" and standards compliant? It works in Firefox but there are many things working as expected in web browsers and aren't by any means standards.

Functions are objects (as you've said), and thus it is possible to add properties to them. This isn't really a standards issue as such in that it is a core part of JavaScript that all browsers support.

Is this kind of altering objects by adding new properties to them a good practice?

It's your object, you can add whatever properties you like. The whole point of objects is that they have properties that you can manipulate. I can't really envisage a way of using objects that doesn't involve altering them, including adding, deleting and updating properties and methods.

Having said that, to me it doesn't really make sense to add properties to the myMethod function, it would be more usual to add other properties to your something object (your myMethod function would, if called correctly, have access to the other properties of something via the this keyword).

If you are using a function as a constructor it typically makes sense to add methods to the associated prototype and add (non-method) properties to each instance, but you can do either or both the other way when appropriate. (Noting that a "method" is essentially just a property that happens to reference a function.)

The specific code you have shown doesn't add properties, it tests whether the someProperty property already exists and if so assigns it a new value.

You might benefit from reading some articles such as these at MDN:

  • Working with Objects
  • Introduction to Object-Oriented JavaScript

Can I add properties to a JavaScript function?

From MDN:

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

Since functions are first-class objects, there is no way of breaking down anything by adding properties to them.

JavaScript: Best way to add custom properties/methods to built-in objects (e.g. arrays)

Method 1 and Method 3 do the same thing. You're just defining functions against an instantiated array. If you're after speed simply stick with methods 1 or 3. Turns out classes extended from array and prototypes from arrays (which is the same thing under the hood) are simply very slow when it comes to large volumes of data. Small cases it's probably fine. I can't seem to find much info on this subject myself either. But hopefully this is a good starting point for further testing. It could take 10ish seconds to complete the test so be patient...

//Method 1
let myArray1 = [];
myArray1.unique = () => [...new Set(myArray1)];
myArray1.last = () => myArray1.at(-1);
//Method 2
class superArray extends Array {
constructor(...items) { super(...items) }
unique(){return [...new Set(this)]}
last(){ return this.at(-1)}
}
let myArray2 = new superArray();
//Method 3
let superArrayMethods = {
unique: function(){return [...new Set(this)]},
last: function(){return this.at(-1)}
}
let myArray3 = [];
myArray3 = Object.assign(myArray3, superArrayMethods);
//Method 4
let superArrayPrototype = {
unique: function(){return [...new Set(this)]},
last: function(){return this.at(-1)}
}
Object.setPrototypeOf(superArrayPrototype,Array.prototype);
let myArray4 = [];
Object.setPrototypeOf(myArray4,superArrayPrototype);

//Timers
console.time("myArray1")
for(i=0; i<10000000; i++) { myArray1.push(i); }
console.timeEnd("myArray1")

console.time("myArray2")
for(i=0; i<10000000; i++) { myArray2.push(i); }
console.timeEnd("myArray2")

console.time("myArray3")
for(i=0; i<10000000; i++) { myArray3.push(i); }
console.timeEnd("myArray3")

console.time("myArray4")
for(i=0; i<10000000; i++) { myArray4.push(i); }
console.timeEnd("myArray4")

console.time("unique myArray1")
myArray1.unique();
console.timeEnd("unique myArray1")

console.time("unique myArray2")
myArray2.unique();
console.timeEnd("unique myArray2")

console.time("unique myArray3")
myArray3.unique();
console.timeEnd("unique myArray3")

console.time("unique myArray4")
myArray4.unique();
console.timeEnd("unique myArray4")

Add Custom Properties for RequestTelemetry of the Azure Function (v3) binding to BlobTrigger

AFAIK there is no http request when using a blob trigger. You can still add custom properties to the telemetry generated during the execution by setting properties like this:

// The current telemetry item gets a property. 
// Useful if the function is not triggered by an http request
Activity.Current.AddTag("setUsingTag", "setUsingTag");

// Subsequent telemetry gets this property attached
Activity.Current.AddBaggage("setUsingActivityBaggage", "setUsingActivityBaggage");

When using Baggage instead of a Tag the custom property is added to all telemetry generated during the execution, like dependency calls etc.

See also this github thread. It also mentions there might be a bug introduced in a later version of AI that might force you to downgrade AI for this to work.


Thanks to this GitHub issue, this is finally working after downgrading System.Diagnostics.DiagnosticSource to version 4.6

<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="4.6.0" />

How can you add custom attributes to a python function object within the function declaration?

You can use a decorator to attached the annotation after the function is defined.

def add_note(k, v):
def _(f):
if not hasattr(f, '_notes'):
f._notes = {}
f._notes[k] = v
return f
return _

@add_note('Dependencies', ['x', 'y'])
def foo(x: int, y: int) -> int:
return x**2 + y**2

As an aside, dunder names (like __notes__) are reserved for the implementation; you should not invent your own. Just use an ordinary "private" name prefixed with a single _.

javascript adding property to function

Function in JavaScript is just an object, it is called Function object.

And just like any other types of object, it has its own constructor (new Function(...)), methods (apply, bind, call...) and properties (arguments, caller, name...) . See the document.

You might be familiar with creating a function like this:

function Rabbit() {
console.log('shiv');
}

Then you should know that you can also create a function like this:

var Rabbit = new Function('console.log("shiv")');

Now, you might guess it out. If you add a new property to a Function object, as long as you don't overwrite the existing one, the function is still working just fine.

do this add a variable bark to function

  • No, the function has it own closure, the only way to add variable to the function is to bind it to this object using Rabbit.bind(object)

do this added a property to Rabbit object

  • Well, since the "Rabbit object" is just an object, Yes.

Add Custom Properties for RequestTelemetry of the Azure Function (v3)

There are some ways. One is like this:

var requestTelemetry = req.HttpContext.Features.Get<RequestTelemetry>();
requestTelemetry.Properties.Add("aProp", "aValue");

The other one is

Activity.Current.AddTag("aProp", "aValue");

I have a full working demo project in a personal repo found here that demonstrates the code in this answer.

Add Custom user Property through firebase function

I was able to do this by making a fetch request to the analytics endpoint by making a function like this. I know this is not recommended but it gets the job done.

let hitGA = () => {
const GA_TRACKING_ID = "your GA tracking ID"
const GA_CLIENT_ID = "steps to get this will be given in the resources below"

const event = {
category: "pricing",
action: "counted",
label: "num_active_users",
value: 71
}
let request = new XMLHttpRequest();
let message =
`v=1&tid=${GA_TRACKING_ID}&cid=${GA_CLIENT_ID}&aip=1&ds=add-on&t=event&ec=${event.category}&ea=${event.action}&el=${event.label}&ev=${event.value}`

request.open("POST", "https://www.google-analytics.com/collect", true);
request.send(message);

}

P.S. if you are curious to know how I stumbled into the solutiona and other references, read this post

How to add custom property of object using .map

use map method and change it into object

let arr = ["1","2"];    arr = arr.map(num => ({id:parseInt(num)}));console.log(arr);


Related Topics



Leave a reply



Submit