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.
我认为您正在寻找getOwnPropertyDescriptor
?
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
You can use Object.getOwnPropertyDescriptor(obj, prop) .
function isGetter (obj, prop) {
return !!Object.getOwnPropertyDescriptor(obj, prop)['get']
}
Usage:
obj = {
foo: 'foo',
get bar() { return 'bar' }
}
isGetter(obj, 'bar') // will return true
isGetter(obj, 'foo') // will return false
Object.defineProperty's
get
orset
Method default value will be undefined if its not defined in the descriptor. This is ideal way to identify.
Let's say example:
var User = {};
Object.defineProperty(User, 'name', {
get: function () {
return _name;
},
enumerable: true
});
Object.defineProperty(User, 'designation', {
get: function () {
return _designation;
},
set: function (val) {
_designation = val;
},
enumerable: true
});
var d = Object.getOwnPropertyDescriptor(User, 'name');
console.log(d.set == undefined);
Find the sample Object template for your java Script requirement:
var Man=function(n,a){
var name,age;
function getName(){
return this.name;
}
function getAge(){
return this.age;
}
function create(){
this.name=n;
this.age=a;
console.log('new object created');
}
function setAge(age){
this.age=age;
}
function setName(name){
this.name=name;
}
return{
name:n,
age:a,
getName:getName,
getAge:getAge,
setName:setName,
setAge:setAge
};
}
var m1=new Man('Chaiguy',30);
// To check if Property exist for an Object
console.log(m1.hasOwnProperty('name'));
// To get the name and age of the object
console.log(m1.getName()+' is '+m1.getAge()+' years old.');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.