`
o_o_0
  • 浏览: 16098 次
  • 性别: Icon_minigender_1
  • 来自: 济南
文章分类
社区版块
存档分类
最新评论

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 ofeval().

{}is synonymous withnew 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!documentandwindoware 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. :-)

分享到:
评论

相关推荐

    javascript语言精粹(中英文版)

    Reflection Section 3.7. Enumeration Section 3.8. Delete Section 3.9. Global Abatement Chapter 4. Functions Section 4.1. Function Objects Section 4.2. Function Literal Section 4.3. Invocation ...

    Reflection-in-OOP

    ## Your Challenge Reflection是面向对象语言中的通用实用程序,用于检查类并派生有关其公开的属性/方法以及它们从其继承的其他类的信息。 今天我们将编写我们自己JavaScript反射器! 我们将编写一个简单的实用程序...

    php-reflection:基于php-parserPHP文件的Nodejs Reflection API

    基于PHP文件的Nodejs Reflection API 安装 npm install php-reflection --save 用法 var reflection = require ( 'php-reflection' ) ; var workspace = new reflection .... '*.inc' , '*.class' , '*.req'

    Understanding.ECMAScript.6.159327757

    ECMAScript 6 represents the biggest update to the core of JavaScript in the history of the language. In Understanding ECMAScript 6, expert developer Nicholas C. Zakas provides a complete guide to the ...

    Mastering Dart(PACKT,2014)

    You will also learn about the collection framework and how to communicate with the different programs written in JavaScript using Dart. This book will show you how to add internalization support to ...

    Learning ECMAScript 6(PACKT,2015)

    ECMAScript 6 is the new edition to the ECMAScript language, whose specifications are inherited by JavaScript. ES6 gives a vast makeover to JavaScript by adding new syntaxes and APIs to write complex ...

    The Dart Programming Language

    based, object-oriented language that simplifies the development of structured modern apps, scales from small scripts to large applications, and can be compiled to JavaScript for use in any modern ...

    The.Dart.Programming.Language.03219277

    based, object-oriented language that simplifies the development of structured modern apps, scales from small scripts to large applications, and can be compiled to JavaScript for use in any modern ...

    .Mastering.Dart.1783989564

    You will also learn about the collection framework and how to communicate with the different programs written in JavaScript using Dart. This book will show you how to add internalization support to ...

    英文原版-Learning ECMAScript 6 1st Edition

    Next, it will teach you how to write asynchronous code in a synchronous style using ES6.Moving on, it will teach you how to create reflection objects, use it to expose hidden object properties, and ...

    HTML Definitive Guide- English Original

    been a reflection of leading-edge thinking about web content from several years ago. This has reduced the importance of the HTML standard because the real innovation was happening away from the W3C, ...

    The Craft of System Security

    12.5 JavaScript to sneakily send POSTs 330 13.1 Example sequence of letters 341 13.2 Looking at Word documents with emacs 342 13.3 Interesting relics in the binary 342 13.4 Turning Fast Save off ...

    java7帮助文档

    You can check the status variable of the applet while it is loading to determine if the applet is ready to handle requests from JavaScript code; see Handling Initialization Status With Event Handlers....

    The.Go.Programming.Language.0134190440.epub

    The book does not assume prior knowledge of Go nor experience with any specific language, so you’ll find it accessible whether you’re most comfortable with JavaScript, Ruby, Python, Java, or C++. ...

    Ajax for Web Application Developers(Ajax网站开发)

    An In-Depth Look at XMLHttpRequest Creating the Object Asynchronous Data Transfers The Ready State HTTP Status Codes and Headers Chapter 3. The Response XML JSON Chapter 4. Rendering ...

    Beginning Microsoft Visual CSharp 2008 Wiley Publishing(english)

    JavaScript 738 Summary 744 Exercises 745 Chapter 21: Web Services 746 Before Web Services 747 Where to Use Web Services 748 Web Services Architecture 751 Web Services and the ...

    CSharp 3.0 With the .NET Framework 3.5 Unleashed(english)

    Accessing Controls via JavaScript 657 Calling Web Services with ASP.NET AJAX 664 Summary 669 29 Crafting Rich Web Applications with Silverlight 670 What Makes Silverlight Tick? 670 Starting...

    值类型与引用类型理论内容.part01.rar

    内容包括:Application Architecture Analysis、Creating the Data Model、Design Database Schema、Programming Stored procedures、Web Application Design、App Setting、 Log in Design、 Security、 ...

    值类型与引用类型理论内容.part05.rar

    内容包括:Application Architecture Analysis、Creating the Data Model、Design Database Schema、Programming Stored procedures、Web Application Design、App Setting、 Log in Design、 Security、 ...

    MagicMeta:用于生成描述魔术配置选项的元数据的实用程序

    万智牌用于生成描述魔术配置选项的元数据的实用程序用法java -jar MagicMeta.jar output.json网站安装创建一个名为config.overrides.inc.php的文件,并将其放在您的Web根目录中。该文件如下所示: &lt;?php$...

Global site tag (gtag.js) - Google Analytics