Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a JavaScript property has a getter or setter defined?

Is it possible, given an object and property name to determine if that property is defined using either a getter or setter, or is it completely transparent? I only want to define a getter/setter if there is not already one defined on the property.

I need it to work in WebKit/Firefox.

like image 577
devios1 Avatar asked Dec 21 '11 15:12

devios1


People also ask

How can you distinguish a getter from a setter?

Getters and Setters play an important role in retrieving and updating the value of a variable outside the encapsulating class. A setter updates the value of a variable, while a getter reads the value of a variable.

Do JavaScript have getters setters?

JavaScript Accessors (Getters and Setters)ECMAScript 5 (ES5 2009) introduced Getter and Setters. Getters and setters allow you to define Object Accessors (Computed Properties).

What is the difference between getter and setter in JavaScript?

Getters and setters allow us to define Object Accessors. The difference between them is that the former is used to get the property from the object whereas the latter is used to set a property in an object.

What is getter and setter properties?

What are Getters and Setters? Getters: These are the methods used in Object-Oriented Programming (OOPS) which helps to access the private attributes from a class. Setters: These are the methods used in OOPS feature which helps to set the value to private attributes in a class.


2 Answers

I think you're looking for getOwnPropertyDescriptor?

like image 86
Graham Avatar answered Sep 17 '22 01:09

Graham


You can use Object.getOwnPropertyDescriptor(obj, prop)

For example:

var obj = { first: 1 } obj.__defineGetter__('second', function() { return 2; });  // get descriptors var descriptor1 = Object.getOwnPropertyDescriptor(obj, 'first'); var descriptor2 = Object.getOwnPropertyDescriptor(obj, 'second');  // check if it's a getter  descriptor2.get // returns function () { return 2; }  descriptor1.get // returns undefined 
like image 35
Jim Schubert Avatar answered Sep 21 '22 01:09

Jim Schubert