Reflection in Javascript

原文

Reflection in Javascript

It’s very easy to do reflection in Javascript. Reflection is when your code looks onto itself to discover its variables and functions. It allows two different Javascript codebases to learn about each other, and it’s useful for exploring third-party APIs.

Preamble

In Javascript, all objects are hashes/associative arrays/dictionaries. A hash is like an array, except that values are associated with unique key string rather than a numeric index.

Adding a new variable to an object is as simple as assigning a new value to a key in the object.

You can declare everything in place:

var o = {
	count: 0,
	name: 'Jane Doe',
	greeting: function() { return "Hi"; }
};
o.greeting();

Or you can start with a blank object and assign things later:

var o = {};

o.count = 0;
o.name = 'Jane Doe';
o.greeting = function() { return "Hi"; };

o.greeting();

Or you can do the same, but in a different notation:

var o = {};

o['count'] = 0;
o['name'] = 'Jane Doe';
o['greeting'] = function() { return "Hi"; }

o.greeting();

The last is especially handy because it allows you to go from the string name of the variable to the variable without the performance penalties of eval().

{} is synonymous with new Object().

Reflection

The loop below pops up a dialog box with the name and value of every variable in object:

for (var member in object) {
	alert('Name: ' + member);
	alert('Value: ' + object[member]);
}

Everything in Javascript is an object. Functions are objects! document and windoware objects. The most reliable reference for Javascript in a given browser is reflection into its innards.

Finally, some slightly more useful code:

/**
	Returns the names of all the obj's
	 variables and functions in a sorted
	 array
*/
function getMembers(obj) {
	var members = new Array();
	var i = 0;
	
	for (var member in obj) {
		members[i] = member;
		i++;
	}
	
	return members.sort();
}

/**
	Print the names of all the obj's variables
	 and functions in an HTML element with id
*/
function printMembers(obj, id) {
	var members = getMembers(obj);
	var display = document.getElementById(id);
	
	for (var i = 0; i < members.length; i++) {
		var member = members[i];
		var value = obj[member];
		display.innerHTML += member + ' = ';
		display.innerHTML += value + '<br>';
	}
}

More sophisticated uses are left as an exercise for the reader. :-)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值