![]() CATEGORIES: BiologyChemistryConstructionCultureEcologyEconomyElectronicsFinanceGeographyHistoryInformaticsLawMathematicsMechanicsMedicineOtherPedagogyPhilosophyPhysicsPolicyPsychologySociologySportTourism |
Type Conversion, toString and valueOfThere are three conversions in JavaScript, which depend on the context: 1. String: output, uses toString. 2. Numeric: maths, operators, uses valueOf -> toString. 3. Boolean: converts according to the table. The algorithm of Object to String conversion 1. If toString method exists and returns a primitive, then return it. 2. If valueOf method exists and returns a primitive, then return it. 3. Otherwise, throw an exception. Again, normally all objects have toString. Built-in objects have their own toString implementations:
Custom toString For our objects, we can implement a custom toString:
Custom valueOf example The magic method valueOf can be customized, just like toString:
That’s different from most other programmer languages, But simple when you get it. P.S. Actually, the conversion is a bit more sophisticated than described here. I’ve left out a good bit of complexity to concentrate on how it really works.
Objects String, Number, Boolean Objects in JavaScript can be converted to primitives in three contexts: 1. String: output, uses toString. 2. Numeric: maths, operators, uses valueOf -> toString. 3. Boolean: converts according to the table. String conversion String conversion happens when a string representation of an object is required. For example, in alert(obj) does it to output obj: var obj = { name: 'John' } alert(obj) // [object Object] Numeric conversion Numeric conversion is performed in two main cases: • In functions which needs a number: for example Math.sin(obj), isNaN(obj), including arithmetic operators: +obj. • In comparisons, like obj == 'John'. The explicit conversion can also be done with Number(obj). The algorithm of numeric conversion: 1. If valueOf method exists and returns a primitive, then return it. 2. Otherwise, if toString method exists and returns a primitive, then return it. 3. Otherwise, throw an exception. Among built-in objects, Date supports both numeric and string conversion: 1 alert( new Date() ) // The date in human-readable form 2 alert( +new Date() ) // Microseconds till 1 Jan 1970 60. Timers: setTimeout and setInterval Browser provides a built-in scheduler which allows to setup function calls for execution after given period of time. SetTimeout The syntax is: func|code Function variable or the string of code to execute. Delay The delay in microseconds, 1000 microseconds = 1 second. The execution will occur after the given delay. For example, the code below calls alert('hi') after one second:
Date: 2016-01-03; view: 1301 |