This document provides an overview of a JavaScript training presentation. It discusses:
- The presenter and their background in software development and TV apps.
- What topics will be covered, including JavaScript principles, vanilla JS, becoming JS ninjas, and specific concepts like prototypes, types, scope, and patterns.
- Benefits of learning JavaScript like it being the language of the web and used for both frontend and backend development.
- Interesting facts about the history and creation of JavaScript.
- Primitive types like strings, numbers, booleans being similar to pizza ingredients, and object types being able to contain other values.
- Syntax for objects, properties, methods, and the prototype
This document discusses Javascript objects. It defines what objects are, how they are created using object literals, the Object constructor, and function constructors. It explains that objects are reference types and compares setting properties using dot notation vs bracket notation. The document also covers the Object.defineProperty method and its uses of enumerable, writable, and configurable properties. It aims to prove that almost everything in Javascript is an object, providing examples of native objects. The document discusses the 'this' keyword and how its value is determined by how a function is called rather than its definition. It compares direct invocation, invoking as an object method, and using call, apply and bind to set the context.
Javascript Prototypal Inheritance - Big PictureManish Jangir
Are you still confused about what the prototypes really are in Javascript. Read the slides from the very begining, you will have a very clear picture about inheritance in Javascript. If you have any questions, please leave a comment. I will try to clarify that thing.
There are a lot of interesting facts that are still unknown and make the Javascript the world's most confusing language. I've tried to explain a few of them if they can help you in better understanding of the JS code.
Javascript uses prototypal inheritance rather than classical inheritance. In prototypal inheritance, objects inherit directly from other objects by using the object's prototype property. The prototype property allows objects to inherit methods and properties from other objects. When accessing a property on an object, Javascript will search the prototype chain to find the property if it is not present on the object itself. This allows code reuse through prototype chaining. The prototype property of a function sets the prototype of objects created with that function.
This document discusses JavaScript prototypes and how they work. It explains that every function has a prototype property that is shared among objects created with that function. It also explains that every object has a hidden __proto__ property that links it to a prototype object. It provides examples of how prototype inheritance works for both classical and prototypal inheritance in JavaScript. Key points covered include how the new operator works, property lookup via the prototype chain, and the relationships between functions, prototypes, and objects in JavaScript.
JavaScript language plays a very important role in Web 2.0 application development. JavaScript has its own characteristics different than object-oriented languages and it's not easy for developers to understand.
This presentation covers major advanced topics in JavaScript languages, including prototype chain, identifier resolving, "this" keyword, "new" operator, execution context and scope chain and closure. Besides that, it also covers best practices when using JavaScript.
Practical and conceptual overview of Javascript prototype paradigm, how to use prototypes, how do they work, and how do they differ from classes, and why there are no real classes in Javascript.
JavaScript has some stunning features like Closures, Prototype etc. which can help to improve the readability and maintainability of the code. However, it is not easy for inexperienced developer to consume and apply those features in day to day coding. The purpose of the presentation ‘Advanced JavaScript’ is to help a reader easily understand the concept and implementation of some advanced JavaScript features.
This document discusses Javascript objects. It defines what objects are, how they are created using object literals, the Object constructor, and function constructors. It explains that objects are reference types and compares setting properties using dot notation vs bracket notation. The document also covers the Object.defineProperty method and its uses of enumerable, writable, and configurable properties. It aims to prove that almost everything in Javascript is an object, providing examples of native objects. The document discusses the 'this' keyword and how its value is determined by how a function is called rather than its definition. It compares direct invocation, invoking as an object method, and using call, apply and bind to set the context.
Javascript Prototypal Inheritance - Big PictureManish Jangir
Are you still confused about what the prototypes really are in Javascript. Read the slides from the very begining, you will have a very clear picture about inheritance in Javascript. If you have any questions, please leave a comment. I will try to clarify that thing.
There are a lot of interesting facts that are still unknown and make the Javascript the world's most confusing language. I've tried to explain a few of them if they can help you in better understanding of the JS code.
Javascript uses prototypal inheritance rather than classical inheritance. In prototypal inheritance, objects inherit directly from other objects by using the object's prototype property. The prototype property allows objects to inherit methods and properties from other objects. When accessing a property on an object, Javascript will search the prototype chain to find the property if it is not present on the object itself. This allows code reuse through prototype chaining. The prototype property of a function sets the prototype of objects created with that function.
This document discusses JavaScript prototypes and how they work. It explains that every function has a prototype property that is shared among objects created with that function. It also explains that every object has a hidden __proto__ property that links it to a prototype object. It provides examples of how prototype inheritance works for both classical and prototypal inheritance in JavaScript. Key points covered include how the new operator works, property lookup via the prototype chain, and the relationships between functions, prototypes, and objects in JavaScript.
JavaScript language plays a very important role in Web 2.0 application development. JavaScript has its own characteristics different than object-oriented languages and it's not easy for developers to understand.
This presentation covers major advanced topics in JavaScript languages, including prototype chain, identifier resolving, "this" keyword, "new" operator, execution context and scope chain and closure. Besides that, it also covers best practices when using JavaScript.
Practical and conceptual overview of Javascript prototype paradigm, how to use prototypes, how do they work, and how do they differ from classes, and why there are no real classes in Javascript.
JavaScript has some stunning features like Closures, Prototype etc. which can help to improve the readability and maintainability of the code. However, it is not easy for inexperienced developer to consume and apply those features in day to day coding. The purpose of the presentation ‘Advanced JavaScript’ is to help a reader easily understand the concept and implementation of some advanced JavaScript features.
By default, every function has a property called prototype this property by default is empty and you can add properties and methods to it and when you create an object from this function. The object inherits its properties and methods.
C/C++ Programming interview questions and answers document discusses key concepts in C++ including encapsulation, inheritance, polymorphism, constructors, destructors, copy constructors, references, virtual functions, abstract classes, and memory alignment. The document provides definitions and examples to explain each concept.
Understanding Object Oriented Javascript - Coffee@DBG JuneDeepu S Nath
You all might have downloaded and edited a lot of javascript. Other than merely changing syntax have you really understood its working or how the code was organised ?
Have you ever thought of how the object oriented way of writing Javascript has been influencing the front end development?
From a language that had helped developers write small validations and similar stuff, today, the object oriented javascript and its frameworks power the world becoming one of the most prominent language of all times.
The document discusses different approaches to object-oriented programming in JavaScript, including classical and prototypal inheritance, constructor functions, and the prototype property. It also covers topics like pseudoclassical patterns, parasitic inheritance, private methods, and debugging and performance techniques.
Encapsulation isolates the internal complexity of an object's operation from the rest of the application. Inheritance allows one class to reuse the state and behavior of another class. Polymorphism allows a client to treat different objects in the same way even if they were created from different classes and exhibit different behaviors.
The document provides an introduction to basic Javascript concepts such as variables, scopes, closures, prototypes, and object-oriented programming principles including inheritance and namespaces over several sections; it also discusses how Javascript code is executed in an execution context and how functions, closures, and prototypes work together to enable OOP functionality in Javascript.
The document provides an overview of the JavaScript programming language, including its history, key concepts, values, operators, statements, and objects. It discusses JavaScript's misunderstood nature due to its name, design errors in early implementations, and use in browsers. Some key points made include: JavaScript is a functional language; it uses prototypal inheritance instead of classes; all values are objects except for primitive values; and functions are first-class objects that can be assigned and passed around.
The document discusses an interview question used to test a programmer's understanding of C++. The question involves writing the assignment operator for a class that contains two pointer data members. A correct implementation of the assignment operator is provided and explained in detail. Key points covered include why assignment operators must be written, the difference between copy constructors and assignment operators, and how to properly define the parameters and return type for an assignment operator.
The document discusses various string methods in Java. It explains concepts like autoboxing, unboxing, string comparison using equals(), ==, compareTo() methods. It also discusses substring, concatenation using concat(), uppercasing/lowercasing using toUpperCase(), toLowerCase() methods. Common string methods like trim(), length(), charAt(), startsWith(), endsWith() are also explained along with examples.
This document discusses several common JavaScript design patterns including Singleton, Factory, Module, Decorator, Command, and Observer patterns. It provides descriptions and code examples for each pattern. The Singleton pattern ensures a class only has one instance and provides a global access point. Factory patterns are used for object creation. The Module pattern provides private and public encapsulation for classes. The Decorator pattern attaches additional responsibilities to objects dynamically. The Command pattern encapsulates requests as objects, and the Observer pattern allows objects to watch other objects for changes.
Java is an object-oriented programming language created by James Gosling at Sun Microsystems in 1995. It is platform independent, meaning programs written in Java can run on any system that supports Java without needing to be recompiled. The document provides an overview of Java, including its history and development, basic concepts like classes and objects, and how to write simple Java programs. It also discusses Java's advantages like being simple, object-oriented, portable, multithreaded, and secure.
The document discusses the module pattern, a design pattern for creating reusable components in JavaScript. It describes how the module pattern allows simulating privacy by wrapping code in immediately invoked function expressions (IIFEs) and returning objects instead of functions. This creates a private scope that is not accessible globally while exposing public APIs. Several examples are given of how different libraries like Dojo, jQuery, YUI, and ExtJS implement the module pattern.
This document discusses autoboxing and unboxing in Java. It explains that autoboxing allows primitive data types to be automatically wrapped into their corresponding wrapper classes when used where an object is expected. Unboxing is the reverse process where the primitive value is automatically extracted from the wrapper class. This simplifies coding by eliminating the need to manually wrap and unwrap values. Autoboxing and unboxing was introduced in Java 5 to make programming with primitive types and wrapper classes more convenient.
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014hwilming
The slide to the Java User Group Talk Exploring Ceylon from Gavin King.
Abstrakt:
Ceylon is a new programming language designed for writing large programs in teams. The language emphasizes readability, modularity, typesafety, and tooling. Ceylon programs execute on Java and JavaScript virtual machines. In this session, Gavin King will talk about the ideas behind Ceylon and demonstrate the language, its type system, its module architecture, and its IDE.
Speaker:
Gavin King leads the Ceylon project at Red Hat. He is the creator of Hibernate, a popular object/relational persistence solution for Java, and the Seam Framework, an application framework for enterprise Java. He's contributed to the Java Community Process as JBoss and then Red Hat representative for the EJB and JPA specifications and as lead of the CDI specification.
Now he works full time on Ceylon, polishing the language specification, developing the compiler frontend, and thinking about the SDK and future of the platform. He's still a fan of Java, and of other languages, especially Smalltalk, Python, and ML.
This document summarizes how to reverse a string in Java with and without using StringBuffer and StringBuilder. It provides code examples of reversing a string using these classes' reverse() method as well as a custom method without them. It also discusses recursion as another approach and compares the different methods.
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
The document provides an overview of JavaScript programming. It discusses the history and components of JavaScript, including ECMAScript, the DOM, and BOM. It also covers JavaScript basics like syntax, data types, operators, and functions. Finally, it introduces object-oriented concepts in JavaScript like prototype-based programming and early vs. late binding.
- Objects in JavaScript store key-value pairs and can contain nested objects and functions. Functions stored as object properties are called methods.
- The this keyword refers to the object a method is called on. Functions can be declared, assigned to variables as expressions, or used as constructor functions with new.
- Scopes in JavaScript are determined lexically at compile time. Variables are stored in execution contexts and functions form closures by maintaining references to outer scopes even after execution leaves them.
- JavaScript uses prototypal inheritance where objects inherit directly from other objects via the internal [[Prototype]] property. The prototype is used to lookup properties not found on the object itself.
This document provides an overview of key JavaScript concepts including data types, objects, functions, arrays, inheritance and common patterns like modules and singletons. It discusses how JavaScript uses prototypal inheritance rather than classical inheritance and how objects inherit properties from the prototype chain. It also covers topics like private variables, privileged methods and the module pattern to organize code.
Slides from Ajax Experience 2009. In this session:
- Object creation patterns
- Code reuse patterns
- Functional patterns
- More on object creation
- Design patterns
Some example patterns: object creation with literals and constructos, prototypes, inheritance and other code reuse patterns, lazy definition, callbacks, singleton, factory, classical and prototypal inheritance, namespaces, chaining, modules, static methods, private and privileged members
For more information, see:
http://jspatterns.com
My column in the JavaScript Magazine (http://jsmag.com)
Blog: http://phpied.com
This is the Google Tech Talk that I gave August 17th, 2007 on building a JavaScript library. I derived much of the talk from my experiences in building the jQuery and FUEL JavaScript libraries.
La Unión Europea ha acordado un embargo petrolero contra Rusia en respuesta a la invasión de Ucrania. El embargo prohibirá la mayoría de las importaciones de petróleo ruso a la UE y se implementará de manera gradual durante los próximos seis meses. Esta medida tiene como objetivo aumentar la presión económica sobre Rusia y privar al país de una importante fuente de ingresos.
By default, every function has a property called prototype this property by default is empty and you can add properties and methods to it and when you create an object from this function. The object inherits its properties and methods.
C/C++ Programming interview questions and answers document discusses key concepts in C++ including encapsulation, inheritance, polymorphism, constructors, destructors, copy constructors, references, virtual functions, abstract classes, and memory alignment. The document provides definitions and examples to explain each concept.
Understanding Object Oriented Javascript - Coffee@DBG JuneDeepu S Nath
You all might have downloaded and edited a lot of javascript. Other than merely changing syntax have you really understood its working or how the code was organised ?
Have you ever thought of how the object oriented way of writing Javascript has been influencing the front end development?
From a language that had helped developers write small validations and similar stuff, today, the object oriented javascript and its frameworks power the world becoming one of the most prominent language of all times.
The document discusses different approaches to object-oriented programming in JavaScript, including classical and prototypal inheritance, constructor functions, and the prototype property. It also covers topics like pseudoclassical patterns, parasitic inheritance, private methods, and debugging and performance techniques.
Encapsulation isolates the internal complexity of an object's operation from the rest of the application. Inheritance allows one class to reuse the state and behavior of another class. Polymorphism allows a client to treat different objects in the same way even if they were created from different classes and exhibit different behaviors.
The document provides an introduction to basic Javascript concepts such as variables, scopes, closures, prototypes, and object-oriented programming principles including inheritance and namespaces over several sections; it also discusses how Javascript code is executed in an execution context and how functions, closures, and prototypes work together to enable OOP functionality in Javascript.
The document provides an overview of the JavaScript programming language, including its history, key concepts, values, operators, statements, and objects. It discusses JavaScript's misunderstood nature due to its name, design errors in early implementations, and use in browsers. Some key points made include: JavaScript is a functional language; it uses prototypal inheritance instead of classes; all values are objects except for primitive values; and functions are first-class objects that can be assigned and passed around.
The document discusses an interview question used to test a programmer's understanding of C++. The question involves writing the assignment operator for a class that contains two pointer data members. A correct implementation of the assignment operator is provided and explained in detail. Key points covered include why assignment operators must be written, the difference between copy constructors and assignment operators, and how to properly define the parameters and return type for an assignment operator.
The document discusses various string methods in Java. It explains concepts like autoboxing, unboxing, string comparison using equals(), ==, compareTo() methods. It also discusses substring, concatenation using concat(), uppercasing/lowercasing using toUpperCase(), toLowerCase() methods. Common string methods like trim(), length(), charAt(), startsWith(), endsWith() are also explained along with examples.
This document discusses several common JavaScript design patterns including Singleton, Factory, Module, Decorator, Command, and Observer patterns. It provides descriptions and code examples for each pattern. The Singleton pattern ensures a class only has one instance and provides a global access point. Factory patterns are used for object creation. The Module pattern provides private and public encapsulation for classes. The Decorator pattern attaches additional responsibilities to objects dynamically. The Command pattern encapsulates requests as objects, and the Observer pattern allows objects to watch other objects for changes.
Java is an object-oriented programming language created by James Gosling at Sun Microsystems in 1995. It is platform independent, meaning programs written in Java can run on any system that supports Java without needing to be recompiled. The document provides an overview of Java, including its history and development, basic concepts like classes and objects, and how to write simple Java programs. It also discusses Java's advantages like being simple, object-oriented, portable, multithreaded, and secure.
The document discusses the module pattern, a design pattern for creating reusable components in JavaScript. It describes how the module pattern allows simulating privacy by wrapping code in immediately invoked function expressions (IIFEs) and returning objects instead of functions. This creates a private scope that is not accessible globally while exposing public APIs. Several examples are given of how different libraries like Dojo, jQuery, YUI, and ExtJS implement the module pattern.
This document discusses autoboxing and unboxing in Java. It explains that autoboxing allows primitive data types to be automatically wrapped into their corresponding wrapper classes when used where an object is expected. Unboxing is the reverse process where the primitive value is automatically extracted from the wrapper class. This simplifies coding by eliminating the need to manually wrap and unwrap values. Autoboxing and unboxing was introduced in Java 5 to make programming with primitive types and wrapper classes more convenient.
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014hwilming
The slide to the Java User Group Talk Exploring Ceylon from Gavin King.
Abstrakt:
Ceylon is a new programming language designed for writing large programs in teams. The language emphasizes readability, modularity, typesafety, and tooling. Ceylon programs execute on Java and JavaScript virtual machines. In this session, Gavin King will talk about the ideas behind Ceylon and demonstrate the language, its type system, its module architecture, and its IDE.
Speaker:
Gavin King leads the Ceylon project at Red Hat. He is the creator of Hibernate, a popular object/relational persistence solution for Java, and the Seam Framework, an application framework for enterprise Java. He's contributed to the Java Community Process as JBoss and then Red Hat representative for the EJB and JPA specifications and as lead of the CDI specification.
Now he works full time on Ceylon, polishing the language specification, developing the compiler frontend, and thinking about the SDK and future of the platform. He's still a fan of Java, and of other languages, especially Smalltalk, Python, and ML.
This document summarizes how to reverse a string in Java with and without using StringBuffer and StringBuilder. It provides code examples of reversing a string using these classes' reverse() method as well as a custom method without them. It also discusses recursion as another approach and compares the different methods.
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
The document provides an overview of JavaScript programming. It discusses the history and components of JavaScript, including ECMAScript, the DOM, and BOM. It also covers JavaScript basics like syntax, data types, operators, and functions. Finally, it introduces object-oriented concepts in JavaScript like prototype-based programming and early vs. late binding.
- Objects in JavaScript store key-value pairs and can contain nested objects and functions. Functions stored as object properties are called methods.
- The this keyword refers to the object a method is called on. Functions can be declared, assigned to variables as expressions, or used as constructor functions with new.
- Scopes in JavaScript are determined lexically at compile time. Variables are stored in execution contexts and functions form closures by maintaining references to outer scopes even after execution leaves them.
- JavaScript uses prototypal inheritance where objects inherit directly from other objects via the internal [[Prototype]] property. The prototype is used to lookup properties not found on the object itself.
This document provides an overview of key JavaScript concepts including data types, objects, functions, arrays, inheritance and common patterns like modules and singletons. It discusses how JavaScript uses prototypal inheritance rather than classical inheritance and how objects inherit properties from the prototype chain. It also covers topics like private variables, privileged methods and the module pattern to organize code.
Slides from Ajax Experience 2009. In this session:
- Object creation patterns
- Code reuse patterns
- Functional patterns
- More on object creation
- Design patterns
Some example patterns: object creation with literals and constructos, prototypes, inheritance and other code reuse patterns, lazy definition, callbacks, singleton, factory, classical and prototypal inheritance, namespaces, chaining, modules, static methods, private and privileged members
For more information, see:
http://jspatterns.com
My column in the JavaScript Magazine (http://jsmag.com)
Blog: http://phpied.com
This is the Google Tech Talk that I gave August 17th, 2007 on building a JavaScript library. I derived much of the talk from my experiences in building the jQuery and FUEL JavaScript libraries.
La Unión Europea ha acordado un embargo petrolero contra Rusia en respuesta a la invasión de Ucrania. El embargo prohibirá la mayoría de las importaciones de petróleo ruso a la UE y se implementará de manera gradual durante los próximos seis meses. Esta medida tiene como objetivo aumentar la presión económica sobre Rusia y privar al país de una importante fuente de ingresos.
No seatbealts = 8x chances of getting killedPODIS Ltd
Drivers and passengers are around 8 times more likely to be killed in a road crash if they are not wearing a seatbelt. (Source: Department of Transport and Main Roads, Queensland)
The PODIS Automatic Crash Notification system reduces road fatalities by minimising the time that first responders are on site.
PODIS: A cloud-based, white-label solution, available globally.
For more information, contact info (at) podis (dot) uk
We have all seen them, most of us have probably worked for them at times, leaders or organisations that are incapable of saying “Sorry, we got it wrong”. A close second is the highly qualified carefully presented half apology “We may have got it a little bit wrong but it really wasn’t our fault, but hey if it helps our position then we are a little bit sorry”.
Whether you are a leader or an organisation there are times when a real apology is essential. All too often this can be delayed for reasons of ego, legal worries or concerns about perception, but often the lack of apology or delay is far more damaging than coming out and admitting you got it wrong, maybe very wrong. So what are the benefits of coming out quickly and publicly and admitting “Sorry we were wrong” or “Sorry I was wrong”?
http://www.workinconfidence.com
The story introduces a magic stone on a distant mountainous island that is watched over by the Sun, Moon, and Wind. One day, the Wind blows gently over the stone, shaping it into the form of a monkey. Over time, the stone monkey comes to life and lives among the other animals on the island.
Aptech maliviya nagar is the best IT training institute in DelhiMCM Infotech
Aptech Malviya Nagar introduces 6 Weeks IT Summer Training program for the young and bright candidates like you who wants to develop and enhance their skills and gain relevant industrial experience to take their career to the next level.
CHRISTIAN SUPERNATURAL TEACHINGS, BIBLE CLASS LESSONS, GOSPELS BY LEADER OLUMBA OLUMBA OBU, THE SUPERNATURAL TEACHER AND SOLE SPIRITUAL HEAD, BROTHERHOOD OF THE CROSS AND STAR
Heather Dennis has written a book paired with a compilation CD to showcase reggae artists and help them gain exposure. Many of the artists featured in the book have faced challenges but continue making music. The book introduces readers to the artists and their personal stories beyond their music in order to make a connection. Heather wrote the book to honor her Jamaican heritage and culture, and reggae music's ability to inspire and bring people together from its origins in Jamaica. She is a business graduate and stay at home mom who also founded a charity to help those in need through supporting causes around children, the elderly, education, and health.
The London Proms has a long history of featuring new works for flute as a solo instrument. This article summarizes 27 works composed since 1895 that have been performed at the Proms, with details on the timing of world premieres and Proms performances. It also discusses the various directors of the Proms and their approaches to programming new flute works over the decades.
The document discusses automation and trends in automation. It provides details about Vinit Vivek such as his name, email, university and area of study. It then discusses how automation uses control systems to operate machinery with minimal human intervention. It notes the benefits of automation in saving labor, energy and improving quality. Finally, it discusses trends in automation like industry 4.0, the internet of things, big data and how industry 4.0 will impact the industry value chain, machine safety, socio-economics and quality of workers.
Este documento discute la lectura como un proceso dinámico y cognitivo en el que el lector construye el significado de un texto. Se describe un modelo interactivo de lectura en el que el lector, el texto y el contexto interactúan. El lector realiza operaciones cognitivas y usa sus conocimientos previos para negociar el significado del texto. El texto ofrece información lingüística, textual y discursiva que el lector usa para comprender.
JavaScript - Programming Languages course yoavrubin
The document provides an overview of JavaScript, covering its dynamic and prototype-based nature, data types including objects and functions, and how functions work including closures and the different ways functions can be called. It discusses key JavaScript concepts like everything being treated as a boolean, prototypal inheritance, and how functions are first-class objects that can be passed around and defined within other functions.
An introductory presentation I'm doing at my workplace for other developers. This is geared toward programmers that are very new to javascript and covers some basics, but focuses on Functions, Objects and prototypal inheritance ideas.
introduction, The Resolution of Property Names on Objects.
Closure
A "closure" is an expression (typically a function) that can have
free variables together with an environment that binds those
variables (that "closes" the expression)
The document discusses JavaScript and some of its key features:
- JavaScript is the programming language of the web browser and was originally developed by Netscape under different names before being standardized.
- JavaScript uses a prototypal object model instead of classes, with objects inheriting directly from other objects via prototypal inheritance chains rather than from classes.
- The "new" keyword is used to create objects but can give the misleading impression of classes; functions can also be used to create objects without "new" by returning the object.
Introduction to javascript and yoolkuiKhou Suylong
This document provides an introduction to JavaScript and the YoolkUi framework. It begins with an overview of JavaScript data types like objects, functions, numbers, strings, and booleans. It then covers JavaScript concepts like objects, arrays, functions, prototypes, inheritance, and the document object model. The document concludes by introducing the YoolkUi framework, describing its components like events, utilities, widgets, and how it handles DOM and object events.
this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality score, this is to check virality scor
Javascript topics covered in the document include prototypes, functions, scope, and "this". Prototypes act like blueprints for objects to inherit properties from. Functions are objects that have a prototype property pointing to their prototype object. Scope is determined by execution contexts and activation objects. The "this" keyword refers to different objects depending on how a function is invoked, such as the containing object for method calls or the global object for regular function calls.
The document discusses Python objects and types. It covers key concepts like object-oriented programming in Python, classes and instances, namespaces, scoping, and exception handling. Some main points include:
- Everything in Python is an object with an identity, type, and value. Objects live in dynamic namespaces and can be accessed via names.
- Classes are type objects that act as templates for creating instances when called. Instances are objects with the same methods and attributes as its class.
- Namespaces are where names are mapped to objects. Python has module, class, and instance namespaces that follow LEGB scoping rules.
- Exceptions are class objects that inherit from the built-in Exception class. The raise statement is used
The document discusses different approaches to object-oriented programming in JavaScript, including classical and prototypal inheritance, constructor functions, and the prototype property. It explains how prototypal inheritance works by linking objects together through their internal prototype properties. Constructor functions and the new operator allow simulating classical inheritance by establishing prototype links. Various design patterns are also covered, such as public/privileged methods, singletons, modules, and parasitic inheritance.
The document discusses different approaches to object-oriented programming in JavaScript, including classical and prototypal inheritance, constructor functions, and the prototype property. It also covers topics like pseudoclassical patterns, parasitic inheritance, private methods, and debugging and performance techniques.
OOP is a programming concept that represents real-world objects like classes and objects. Some key aspects of OOP include:
- Classes define common properties and methods for objects through data abstraction.
- Objects are instances of classes that reserve memory at runtime.
- Polymorphism allows common interfaces for different objects through concepts like inheritance and method overriding.
- Inheritance allows classes to inherit properties from parent classes to extend functionality.
Powerful JavaScript Tips and Best PracticesDragos Ionita
The document provides 11 powerful JavaScript tips and best practices for programmers, including using short-circuit evaluation to set default values, immediately invoked function expressions to avoid polluting the global namespace, and splice instead of delete to remove array items without leaving undefined holes.
Enumerable provides a large set of useful methods for enumerations or collections of values. It is a core module that allows objects to be iterated over. Enumerable provides aliases for some methods and optimized versions for common use cases like invoking the same method on each element or fetching the same property from each element. To use Enumerable, an object just needs to provide an _each method that iterates over its elements.
The document provides an overview of JavaScript design patterns including creational, structural, and behavioral patterns. It discusses common patterns like the module pattern, prototype pattern, factory pattern, decorator pattern, observer pattern, and more. Code examples are provided to demonstrate how each pattern works in JavaScript.
this talk is about some of the features of Javascript that are not always good understood by developers like me (that are mainly back-end and work mainly in c# or Java)
This document provides an overview of advanced JavaScript concepts beyond jQuery, including traversing the DOM, element objects, functions, native objects, closures, manipulating data with array methods, prototypal inheritance, revealing modules, and function composition. It discusses using vanilla JavaScript instead of jQuery for DOM manipulation and events. It also explains JavaScript functions, closures, and how functions are first-class citizens that can be assigned to variables and passed as arguments. The document outlines prototypal inheritance in JavaScript and alternative patterns like factories and composition. It provides examples for working with arrays, closures, and building reusable objects.
This document provides an overview of object-oriented programming concepts in JavaScript, including objects, classes, encapsulation, inheritance, and the prototype pattern. It explains how to create objects, define methods, extend objects through prototypes, implement inheritance through prototypal inheritance and mixins, and use the module pattern to create private variables and functions within objects.
The document discusses JavaScript functions and execution contexts. It explains that functions are first-class objects that can be stored in variables, objects, and arrays. It also discusses how functions are interpreted, including how variable instantiation and scoping work due to hoisting. The document explains that the value of "this" depends on how a function is invoked, as a method, constructor, function literal, or with call/apply. It also discusses closures and how they close over variables from the scope they were created in.
Class.js is a small JavaScript library that provides class-like inheritance. It allows defining classes that inherit properties and methods from a parent class. The library is only 25 lines long and uses a clever approach of caching method references to enable calling super methods from subclasses. While useful for defining common APIs across related types, Class.js is generally not needed in idiomatic JavaScript which favors composition over classes.
The document discusses JavaScript inheritance. It explains that JavaScript uses prototype-based inheritance rather than class-based inheritance. It provides examples of how to implement inheritance by linking object prototypes together through the __proto__ property or Object.create method. Functions in JavaScript have a prototype property that is used to inherit properties and methods onto objects created with new.
Instagram has become one of the most popular social media platforms, allowing people to share photos, videos, and stories with their followers. Sometimes, though, you might want to view someone's story without them knowing.
Gen Z and the marketplaces - let's translate their needsLaura Szabó
The product workshop focused on exploring the requirements of Generation Z in relation to marketplace dynamics. We delved into their specific needs, examined the specifics in their shopping preferences, and analyzed their preferred methods for accessing information and making purchases within a marketplace. Through the study of real-life cases , we tried to gain valuable insights into enhancing the marketplace experience for Generation Z.
The workshop was held on the DMA Conference in Vienna June 2024.
Ready to Unlock the Power of Blockchain!Toptal Tech
Imagine a world where data flows freely, yet remains secure. A world where trust is built into the fabric of every transaction. This is the promise of blockchain, a revolutionary technology poised to reshape our digital landscape.
Toptal Tech is at the forefront of this innovation, connecting you with the brightest minds in blockchain development. Together, we can unlock the potential of this transformative technology, building a future of transparency, security, and endless possibilities.
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBrad Spiegel Macon GA
Brad Spiegel Macon GA’s journey exemplifies the profound impact that one individual can have on their community. Through his unwavering dedication to digital inclusion, he’s not only bridging the gap in Macon but also setting an example for others to follow.
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdfFlorence Consulting
Quattordicesimo Meetup di Milano, tenutosi a Milano il 23 Maggio 2024 dalle ore 17:00 alle ore 18:30 in presenza e da remoto.
Abbiamo parlato di come Axpo Italia S.p.A. ha ridotto il technical debt migrando le proprie APIs da Mule 3.9 a Mule 4.4 passando anche da on-premises a CloudHub 1.0.
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC
Ellisha Heppner, Grant Management Lead, presented an update on APNIC Foundation to the PNG DNS Forum held from 6 to 10 May, 2024 in Port Moresby, Papua New Guinea.
2. About me
- software developer at
- making TV apps with JavaScript
- invested the last 12 years of my life doing this:
3. What are we going to learn today?
- the most important JavaScript principles and
basics that will keep you safe
- mostly vanilla JavaScript stuff, there will be
no Angular or whatever during this lecture
- you have to become JS ninjas today!
4. Just some of the things you will
learn about today...
prototype chain call/apply types in JavaScript
this objects internal properties
scope chain type coercion truthy/falsy
closures try/catch undefined
hoisting caching singleton
IFFY (immediately-invoked function expression) setTimeout/setInterval
behavioral inheritance revealing module pattern namespacing pattern
5. Benefits of learning JavaScript
- “the language of the Web”
- JavaScript is used in 89% of all web-sites
- both frontend AND backend (NodeJS)
6. Interesting facts
- created by Brendan Eich in May 1995 while
he was part of Netscape
- original name Mocha, then for marketing
purposes renamed to LiveScript (could not
use Java in the name in the beginning
because of a trademark argument with Sun)
- Java keywords, but inspired by functional
languages on the inside
7. Interesting facts
- JavaScript is based on a standard called
ECMAScript
- ECMAScript is managed by TC39
- next version is always called ES.Next
- new features are always called ES.Harmony
8. What a pizza consists of? (don’t
worry, it’s still JavaScript
presentation)
9. What a pizza consists of? (don’t
worry, it’s still JavaScript
presentation)
Depends, but usually:
- cheese
- tomato
- ham
- sauce
- eggs (even more ...)
10. Simple ingredients
Ingredients that can not be divided any further:
Example: Tomato - a tomato is just a tomato. It
does not consist of anything else.
11. Complex ingredients
Consist of more than one ingredient:
Example: sauce - consists of chilly peppers,
tomato, etc., etc.
12. So back on the main topic…
JavaScript basic types are similar to
pizza ingredients!
13. Primitive types - values that can not be
divided any further
- string
- number
- boolean
- null // digital equivalent of nothing
- undefined // variable with no value assigned
Object types - values that can contain several
other values/composite values
- Object
17. What is the common thing between
objects? (continued)
ANSWER: Every object is an abstraction.
You don’t have to know what happens inside of it, to be able to use it.
Objects do something. Usually you don’t know how exactly they do it.
18. Built-in types in JavaScript
Array
Boolean // wrapper around boolean primitive type
Date
Function // allows for invoking code
Math
Number // wrapper around number primitive type
RegExp
String // wrapper around string primitive type
19. Number, String, Boolean !== number, string, boolean
Object type of Number, String, Boolean is “Object”!!
22. Object literal notation (when you
know the values beforehand)
var variableName = {
propertyName1: value,
propertyName2: value,
// .... etc.
};
23. Object properties (the dynamical
approach)
obj.propertyName = value;
or
obj[“propertyName”] = value;
24. Defining object methods (dynamic
notation)
obj.methodName = function () {
// this points to the instance of the object!!
alert(this.objProperty1); // outputs the value of specific
property of this object instance
};
25. Object internal properties
Every object has a [[Prototype]] or __proto__ internal
property that points to its prototype Object.
Basically objects are like humans - they were created to
look like God (in their case their prototype) ;)
All of their properties are derived from the prototype
object.
26. Object prototype explained in
another way
An object is like a kid that has no money.
Its parent has a credit card with money.
Everytime it needs to buy something, the object asks his
parent to buy it for him.
27. Object prototype explained in
another way
An object is like a kid that has no money. (in this case no
specific property)
Its parent has a credit card with money. (in this case the
parent has such property)
Everytime it needs to buy something, the kid asks his
parent to buy it for them. (in this case the object asks the
parent for the parent’s property)
28. Prototype chain
- this whole ask the parent if I can’t do it myself thing…
- [[Prototype]] property points to the parent, so that’s what
the JavaScript engine uses to find the parent and “ask”
them
- we are traversing the prototype chain until we find
parent that has the property or reach the point in which
we try to access the [[Prototype]] internal property of the
Object type itself ([[Protype]] ⇒ null in that case...)
29. Prototype chain API
- hasOwnProperty(prop); // checks whether the object
instance has a “prop” property WITHOUT traversing the
prototype chain (we are looking for the property directly
on the instance)
31. Inheritance
var Animal = function () {
this.name = “private value”;
};
Animal.prototype = { // the interface
func1: function () {
console.log(this.name);
},
func2: function () {
}
}
var cat = new Animal();
32. Inheriting from another class
function Cat() {
}
Cat.prototype = new Animal(); // or Cat.prototype = Object.create(Animal.
prototype)
var cat = new Cat();
console.log(cat instanceOf Animal); // we expect to get true here...
33. Why Cat.prototype = Animal.
prototype does not work (DEMO)
Any changes to Cat.prototype will change Animal.prototype and that is not what
we want!
34. Creating instance variables
function ClassName () {
// put instance variables in the constructor function
// because here we have access to the newly-created instance
this.instanceVar = “value”;
}
IMPORTANT: Because of prototype chain traversal
this.instanceVar in the constructor function will always execute ahead of
ClassName.prototype.instanceVar. That’s how things work. Instance
methods/properties are executed before prototype methods/properties.
35. Creating getters/setters
function ClassName () {
// put instance variables in the constructor function
// because here we have access to the newly-created instance
this.instanceVar = “value”;
}
// put getters/setters in the prototype, not on the instance itself!
ClassName.prototype.getValue = function () {
return this.instanceVar;
};
36. The constructor property
var c = new ClassName();
// because we attach methods to ClassName.prototype (ClassName is the
constructor function) we can get prototype by doing:
ClassName.constructor.prototype
37. Modifying the prototype chain of an
object
- How to set the [[Prototype]] property of specific object to
point to another parent?
38. Enter the Object.create method...
- this method creates a new object
- and sets its [[Prototype]] property to what we want
var obj = Object.create(prototypeObject);
or
var obj = Object.create(prototypeObject, { prop1: { value:
theValue }, prop2: { value: theValue2 } }); // second
argument allows you to initialize some properties of the
new object instance. Not very pretty, but works.
40. The 4 rules for the value of this
Value of this in a specific function depends on where and
how the function was called.
- is it called with new()?
- is it called with .call or .apply?
- is it called like obj.func()?
- is it called like func()?
41. The 4 rules for the value of this
Value of this in a specific function depends on where and
how the function was called.
Let’s say we have a function called func().
Let’s answer those 4 questions for it:
1. Is it called with new()?
2. Is it called with .call or .apply?
3. Is it called on object instance (example: obj.func())?
4. Is it called by itself (example: func())?
42. Rule #1: Is it called with new()?
var a = new func();
- putting the new keyword before a function name turns
the function into a constructor call
43. How constructors work?
They do 4 things:
1. Create a brand new empty object
2. They link the object to a prototype
3. this => the brand new empty object
4. Compiler returns this; (or the new object) if nothing else
returned explicitly
44. Hence...
If func() was called like this:
var obj = new func();
this will be equal to obj (the new instance).
45. Rule #2: Is it called with call or
apply?
Like this:
func.call(this);
or this:
func.apply(this);
46. Sidenote: what are those call and
apply functions, dude?
functionName.call(valueOfThis, arg1, arg2, ... , argN);
functionName.apply(valueOfThis, [arg1, arg2, ... , argN]);
Those functions basically do the same. They allow us to
call a function with explicit value for this inside of the
function.
How to remember what’s what:
Call = Comma (arguments separated with comma)
Apply = Array (arguments in array object)
47. Call and apply create explicit binding
var a = {};
func.call(a); // this === a
48. When rule #2 is present this === the
explicit object
49. Rule #3: Is it called on object
instance?
Example:
var a = obj.func(); // this === obj
obj2.func(); // this === obj2
This is called implicit binding.
50. Rule #4: Is it called by itself?
Example:
func(); // this === global object/window or undefined if we
are at “strict mode”
This is called default binding.
52. Back to inheritance...
var person = {
getName: function () {
return this.firstName + “ “ + this.lastName;
}
};
var john = Object.create(person);
john.firstName = “John”;
john.lastName = “Smith”;
// Why this works??
53. Back to inheritance (2)
this keyword refers to initial object that we are traversing
the prototype chain for… (the kid)
54. The prototype keyword
Allows you to extend built-in or custom classes with more
functionality:
obj.prototype.functionName = function () {
// again this points to the object that is requesting the
method (a.k.a. the kid, a.k.a. the object instance)
alert(this.propValue);
};
56. JavaScript type coercion
var var1 = “42”,
var2 = 42;
console.log(var1 == var2); // logs out “true”
When comparing values like this, JavaScript forces the
values to be from the same type under the hood. Which is
not always good and can lead to not understanding what’s
going on (never good).
BEST PRACTICE: Always use strict equality operators ===
and !== (they check for both type and value)
58. null
typeof null // returns “object”????! (although it is a primitive
type - long-standing bug at JavaScript engine - should be
fixed soon)
var variable1 = null; // when we want a variable to have
“empty” value on purpose
59. undefined
var variable;
console.log(variable); // no value is set yet => returns
undefined
function doNothing() {
return;
}
console.log(doNothing()); // yep. undefined.
typeof undefined // returns “undefined”
60. Comparing with undefined
Don’t do this:
if (var1 == undefined) {
// execute code here
}
because you or somebody else could set undefined to some other
value and then… BANG!
61. The worst-case scenario realized
function testUndefined() {
var undefined = 5,
a = 5;
if (a == undefined) {
// this will be executed. Surprise, surprise!
}
}
62. How do I fix this?
function testUndefined() {
var undefined = 5,
a = 5;
if (typeof a === “undefined”) {
// typeof a is “number”. We are not reaching this place!
}
}
// remember how typeof undefined is “undefined” and typeof null is
“object”? See, this knowledge is not so worthless?
63. Initialization with boolean operators
function printName(user) {
var name = user.name || default_value,
streetName = user && user.address && user.address.
streetName;
}
64. Question: What will this code
output?
function aMethod() {
console.log(a);
if (true) {
var a = 0;
}
}
65. Answer:
If you guessed 0, you were wrong. You see, behind the
scenes the JavaScript engine in your browser of choice
goes through each JavaScript function and FIRST THING
BEFORE IT EXECUTES THE FUNCTION IT DOES A
LITTLE RITUAL EVERY SINGLE TIME… Check next slide
to see what it is...
66. VARIABLE HOISTING
The JavaScript engine moves all var statements to the
VERY BEGINNING of the function.
The value assignments ARE NOT MOVED, ONLY the
variable declarations!
So after this little ritual the browser modifies the code like
this...
67. Question: What will this code
output?
function aMethod() {
var a;
console.log(a); // ANSWER: undefined!
if (true) {
a = 0;
}
}
68. The consequences of variable
hoisting
- it’s always best if your source code does exactly what it
looks like it’s doing
- if we know the JavaScript engine will move the variable
declarations to the top of a function, then we should
move them there beforehand, so that this process is
obvious to JavaScript beginners looking at our source
code as well!
69. Another question: what is going to
be outputted here?
var a = 2;
function aMethod() {
function bMethod() {
var a = 0;
if (true) {
var b = 30;
}
console.log(a);
}
}
70. HINT: What is b in this case?
var a = 2;
function aMethod() {
function bMethod() {
var a = 0;
if (true) {
var b = 30;
}
console.log(a);
}
}
71. Answer:
In this context b is a LOCAL VARIABLE for the bMethod
function.
In other programming languages we would expect that b is
only visible in the if code block (the space between the
opening { and the closing }) (i.e. it has block scope).
But in JavaScript, variables are visible from the beginning
of a function to its end, i.e. they have function scope.
72. … but where is my answer to the
first question?
in order to answer it we need to understand how the
SCOPE CHAIN works.
73. THE SCOPE CHAIN (1)
When you mention a variable’s name inside of a function,
JavaScript goes through the Scope resolution process. It’s
a step-by-step process until the variable is found/resolved.
Let’s imagine that in the bMethod function from the
example above we were mentioning a variable called c.
74. THE SCOPE CHAIN (2)
The steps executed by the JavaScript engine are listed below:
1. Check for local variable with the name c. If it does not exist, continue the
traversal process, otherwise stop and use the value.
2. See parent function and check for local variable in it named c. If it does not
exist, continue the traversal process, otherwise stop and use the value.
3. Repeat 2. until the window object (remember that global variables are
properties of the window object) is reached and check again for a global
variable with that name. Return undefined if no such variable exists,
otherwise return the value.
Question: What is faster in your opinion - looking for a global variable from
within a function nested in 30 another functions or using a local variable in that
function?
Answer: Of course, each additional step in the scope chain traversal takes the
browser some time. Each step matters and adds up.
75. Caching variables is VERY GOODIt is a good idea to cache variables when:
- in our function we are going to use a variable that takes a while to be found
in the scope chain A COUPLE OF TIMES
Example:
var veryFarAwayVariable = 0;
function function1() {
function function2() {
…
function functionVeryDeep() {
var vf = veryFarAwayVariable; // traverse the whole chain only once
(because life and users’ patience are pretty short)
vf++;
Math.sqrt(vf);
}
76. So, finally we got the answer right!
var a = 2;
function aMethod() {
function bMethod() {
var a = 0;
if (true) {
var b = 30;
}
console.log(a); // you see 0.
}
}
77. JavaScript namespaces and why
they are useful
var com = {
strypes: {
appName: {
}
}
};
var appNS = com.strypes.appName;
The chances that the global com variable is overriden are
bigger than those for com.strypes.appName.
78. Let’s talk about code conventions (1)
- “I want to avoid idioms that look like
mistakes.” - Douglas Crockford
- if ( // put space between if and ( because
otherwise if( looks like function invocation
- tabulation = 4 spaces
- put space after every , or :
79. Let’s talk about code conventions (2)
- put { in the end of line instead of beginning
of it
return // WILL RETURN UNDEFINED!!!
{
obj: value
};
80. Let’s talk about code conventions (3)
- declare variables in the beginning of the
function (it is best to use a single var)
- why: because we have function scope, not block
scope
var variableName1 = value,
variableName2 = value2,
variableName3 = value3;
82. An example for IFFY
(function () {
var localVar = 0;
})();
What we know about this?
- it executes immediately (see the () - the symbol for calling a
function)
- all local variables inside will be removed immediately after
execution (the memory they took will be set free for use by other
processes on the computer)
- it’s an expression (see the brackets around the function? They
make it an expression. Without them you will get a syntax error.)
- because local variables act like local variables, they are
unreachable by third party apps which means that this approach is
(kind of) PRIVATE and SAFE.
83. Why the revealing module pattern is
“kool”
- uses the IIFE pattern to encapsulate private information
- remember objects and how you didn’t knew what they were doing
deep inside? Do you think your grandmother wants to know how
her TV works? Just using the TV interface (the TV remote) is hard
enough for her, no?
- you have private and public parts, which means even your
grandmother can (probably) use your code.
84. The revealing module pattern
example
(function () {
var privateVar = “value”;
function privateMethod() { // you can not access this without the help of
the ubiquitous Chrome DevTools :)
return privateVar; // returns “value”
}
return { // now this is the public part:
publicMethodName: privateMethod
}
})();
85. Singleton pattern example
- useful when we should allow for the creation of only one instance of
specific object
- see singleton.js in code/ directory
86. function quotatious(names) {
var quotes = [];
for (var i = 0; i < names.length; i++) {
var theFunction = function () {
return “My name is “ + names[i] + “!”;
}
quotes.push(theFunction);
}
return quotes;
}
var people = [“Tony Stark”, “John Rambo”, “James Bond”, “Rick James”];
var peopleFunctions = quotatious(people);
var person = peopleFunctions[0](); // we expect “My name is Tony Stark!” here, no?
87. CLOSURE
A safe “bubble” around a function that:
- keeps all of the outer variables that the function is using alive until it executes
- the bubble knows only the address of the variable it’s protecting, NOT THE
VALUE ITSELF!
88. function quotatious(names) {
var quotes = [];
for (var i = 0; i < names.length; i++) {
var theFunction = function () {
return “My name is “ + names[i] + “!”;
}
quotes.push(theFunction);
}
return quotes;
}
Sooo… if all we have is an address in memory (no value),
what do we know about the i variable? And what is it latest
value of that variable? See what the problem is?
89. Answer: all returned functions will have only a reference to
the value of i (the space in memory dedicated to that
variable) and what is there currently is the following
number:
4
It WAS a trap, indeed.
90. DEMO:
Looking at some JS design patterns in the source code of
some frameworks:
http://backbonejs.org/docs/backbone.html
https://github.com/emberjs/ember.js/
https://github.com/angular/angular.js/
91. Short detour… What browsers do
when loading a page?
1. [User] Type URL and press Enter or click a link
2. [Browser] Make request to download page .HTML file
3. [Browser] Parse .HTML and populate DOM tree.
(images and stylesheet have not been parsed yet, you
only see content) // DOMContentLoaded event fired.
4. [Browser] Load images and stylesheets (generate
Render tree)
5. [Browser] Load scripts and wait for each script to
execute // page fully loaded. load event fired.
92. How browsers parse an HTML file
Tokenizer - knows the “dictionary” of HTML and breaks
down the HTML file into tokens/words
Parser - receives “words” from the Tokenizer and builds
with them:
1. Parsing HTML to Construct the DOM tree
2. Render tree construction =
93. Scripts order in DOM matters
1. Browser walks the DOM from top to bottom.
2. When a browser finds a <script> tag, it downloads and
executes the scripts and STOPS EVERYTHING else on
the page from running while the script is executing!!!!!
(hence the page will appear to be frozen/including there
will be no mouse/keyboard events)
BEST PRACTICE 1: Place script tags in the bottom of the
page (show the page to users and then wait for scripts to
execute)
BEST PRACTICE 2: Use <script async> (runs script
without blocking other stuff) and <script defer> (delays
running a script after DOM is loaded)
94. <script defer>
The <script defer> attribute indicates that the script
contained within the element is not going to MODIFY THE
DOM and therefore execution can be safely deferred until a
later point in time.
JavaScript will execute ONLY AFTER the DOM has loaded.
95. Other notes about the <script> tag
While a script is downloaded and/or executed, most
browsers can not download anything else (for example:
images, stylesheets, etc.).
“Each HTTP request brings with it additional performance
overhead, so downloading one single 100 KB file will be
faster than downloading four 25 KB files.” - Nicholas Zakas,
“High Performance JavaScript”
96. Other interesting notes about how
browsers work (1)
Most browsers use one single process for both:
- updating the UI (including user events, e.g. mouse
clicks, key presses, etc.)
- executing JavaScript code
As a consequence while JavaScript code is running, mouse
clicks are not detected (the application looks frozen to the
user).
97. Other interesting notes about how
browsers work (2)
Browsers can download CSS files in parallel (this is a non-
blocking operation)
Browser UI Thread process - there is only one process that is
responsible for both:
- executing JavaScript code
- updating the UI/the screen
Hence: while JavaScript is executing you can not update the
screen (you can not do both at the same time). Hence it is
important to divide huge processing operations in batches.
98. Garbage Collection (GC) in the
browser
- the browser goes through all objects and removes the
unnecessary ones to free up some more memory for useful
things
99. setInterval vs setTimeout (1)
- setTimeout(function, n)
- executes code after n milliseconds
- setInterval(function, n)
- executes code every n milliseconds
102. setInterval vs setTimeout (2)
- browsers use one single process to:
- update UI
- execute JavaScript code
=> browser does not receive user events while
executing JavaScript code
=> before the Web Workers API all JavaScript
executed in ONE thread. ONE.
103. Consequences of having a single
thread for JavaScript code execution
Handlers for asynchronous events such as:
- timers
- UI events (click, doubleclick, touch, etc.)
- XMLHttpRequests
execute ONLY when there is nothing else
executing on the JS thread. Otherwise the
browser puts the handler in a special queue.
104. Why am I telling you this?
- users nowadays notice even the slightest
interaction delays
- are you okay with family get-together with
uncle Vanio talking all the time?
105. The solution:
- convert blocking operations into non-
blocking operations
- execute costly operations piece by piece
with timers
- make uncle Vanio shut up from time to time
- execute -> suspend -> execute next part ->
suspend
107. setInterval and setTimeout - final
notes
- use only timer at a time - this way we
prevent performance issues which can occur
if we use multiple timers at the same time
(GC)
108. Try… Catch
try {
// some risky code goes here
// and it might throw exception
} catch (exceptionInfo) {
// block scope goes here. hmm..?!
}
109. Things to avoid in JavaScript
“When reviewing the features of a language, I now pay
special attention to features that are sometimes useful but
occasionally dangerous. Those are the worst parts because
it is difficult to tell whether they are being used correctly.
That is a place where bugs hide. (...) JavaScript provides
support for large programs, but it also provides forms and
idioms that work against large programs.”
Douglas Crockford
110. What’s next in ES 6?
- Generators
- Modules (export)
- Arrow functions
- Classes (syntax sugar)
- Destructuring
- Tail calls
- Promises
- The let keyword
and more...
114. - takes source code and scans it for
problematic code
- setting up SublimeText with JSLint
Code Quality Tools for JavaScript
115. Recommended sites
- https://developer.mozilla.org/ a.k.a. MDN
- more detailed than W3School
- more up-to-date because it is an open wiki (most of
the articles are not written by Mozilla, they are
written by web developers like you and me!)
- frontendmasters.com // Dido will probably
give you access to this one. Some
lifechanging lectures in there!