您的位置:首页 > Web前端 > JavaScript

NOTE: javascript prototype chain

2009-02-11 09:31 295 查看
=== copy from mastering dojo ===

What Is a Prototype?
Every object in JavaScript contains a reference to another
object termed its prototype. Since the prototype is another
object itself, it also contains a reference to its prototype. This
forms a chain of objects. The chain terminates with the prototype
for the built-in Object type.
When a property of an object is read, JavaScript looks for the
property in the object. If not found, JavaScript then looks in the
prototype object, the prototype of the prototype, and so on,
up the prototype chain until the property is found or the chain
is exhausted. Since a method is just a property that happens to
be a function, this is how method dispatching occurs, and this
system is called prototypal inheritance.

=== test ===

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test prototype</title>
<body>
<div id="debug"></div>
<mce:script type="text/javascript"><!--
var obj = {a:-1, b: 1};
var TMP = function(){};
TMP.prototype = obj;
var tmp = new TMP();
document.getElementById('debug').innerHTML += ("obj.a: " + obj.a) + '<br />';
document.getElementById('debug').innerHTML += ("tmp.a inherit from obj: " + tmp.a) + '<br />';
document.getElementById('debug').innerHTML += '<br />';
obj.a = 0;
document.getElementById('debug').innerHTML += ("obj.a = " + obj.a) + '<br />';
document.getElementById('debug').innerHTML += ("tmp.a: " + tmp.a) + '<br />';
document.getElementById('debug').innerHTML += '<br />';
tmp.a = 1;
document.getElementById('debug').innerHTML += ("tmp.a = " + tmp.a) + '<br />';
document.getElementById('debug').innerHTML += ("obj.a not changed: " + obj.a) + '<br />';
document.getElementById('debug').innerHTML += ("tmp.a: " + tmp.a) + '<br />';
document.getElementById('debug').innerHTML += '<br />';
obj.a = -100;
document.getElementById('debug').innerHTML += ("obj.a = " + obj.a) + '<br />';
document.getElementById('debug').innerHTML += ("tmp.a: " + tmp.a) + '<br />';
document.getElementById('debug').innerHTML += ("TMP.prototype.a: " + TMP.prototype.a) + '<br />';
// --></mce:script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: