comparison core-javascript/core-javascript-work/tutorial.js @ 141:e8bfe6c50a01 core-javascript

Add commentary to what-is-new.rst.
author Jonathan Fine <jfine@pytex.org>
date Mon, 31 Oct 2011 21:17:17 +0000
parents abfb176c7346
children
comparison
equal deleted inserted replaced
140:abfb176c7346 141:e8bfe6c50a01
166 166
167 167
168 // start new-operator 168 // start new-operator
169 TEST('new-operator', function() 169 TEST('new-operator', function()
170 { 170 {
171 // A 'traditional class'. It records 'this' as a side effect.
171 var this_in_Fn; 172 var this_in_Fn;
172
173 var Fn = function(){ 173 var Fn = function(){
174 this_in_Fn = this; 174 this_in_Fn = this;
175 }; 175 };
176 176
177 this_in_Fn = null; 177 // Call the 'class' without the 'new'.
178 this_in_Fn = null; // Clear any previous value.
178 var non_instance = Fn(); 179 var non_instance = Fn();
179 assert( non_instance === undefined ); 180 assert( non_instance === undefined );
180 assert( this_in_Fn.telltail === 'global'); 181 assert( this_in_Fn.telltail === 'global');
181 182
182 this_in_Fn = null; 183 // Call the 'class' with the 'new'.
184 this_in_Fn = null; // Clear any previous value.
183 var instance = new Fn(); 185 var instance = new Fn();
184 assert( instance === this_in_Fn ); 186 assert( instance === this_in_Fn );
185 assert( instance.telltail === undefined ); 187 assert( instance.telltail === undefined );
186 188
189 // Demonstrate that instance is a descendant of Fn.prototype.
187 Fn.prototype.telltail = 'instance-of-Fn'; 190 Fn.prototype.telltail = 'instance-of-Fn';
188 assert( instance.telltail === 'instance-of-Fn' ); 191 assert( instance.telltail === 'instance-of-Fn' );
189 192
190 Fn.prototype = { 193 // We can give Fn a new prototype.
191 telltail : 'prototype-is-changed' 194 instance.new_telltail = 'child-of-instance';
192 }; 195 Fn.prototype = instance;
196
197 // And now an instance of Fn has two telltails.
193 var second_instance = new Fn(); 198 var second_instance = new Fn();
194 assert( second_instance.telltail === 'prototype-is-changed' ); 199 assert( second_instance.telltail === 'instance-of-Fn' );
195 200 assert( second_instance.new_telltail === 'child-of-instance' );
196 Fn.prototype = second_instance;
197 second_instance.i = 42;
198
199 var third_instance = new Fn();
200 assert( third_instance.telltail === 'prototype-is-changed' );
201 assert( third_instance.i === 42 );
202 201
203 }); 202 });
204 // end new-operator 203 // end new-operator