javascript for c# programmers - sdd conferencesddconf.com/brands/sdd/library/jsforcs.pdf ·...
TRANSCRIPT
© 2010 RoCk SOLiD KnOwledge Ltd.
JavaScript for C# Programmers
Kevin Jones
@kevinrjones
http://www.github.com/kevinrjones
© 2010 RoCk SOLiD KnOwledge Ltd.2
Types
Basic Syntax
“Objects”
Functions
Agenda
© 2010 RoCk SOLiD KnOwledge Ltd.3
Basics
'C' like language
braces
brackets
functions
function doSomething(){}
© 2010 RoCk SOLiD KnOwledge Ltd.4
Variables
Use var to introduce variables
Not typed (mostly)
Use ‘let’ in ES6
Better scoping
var age = 1;var name = "Alice";
if(age > 18) {let isAdult = true;...
}
for ( let i=i ; i < 10 ; i++ ) { console.log(i);
}
© 2010 RoCk SOLiD KnOwledge Ltd.5
Types
JavaScript has a limited number of types
Object
Number
String
Function
Boolean
Undefined
Null
© 2010 RoCk SOLiD KnOwledge Ltd.6
Equality
Be afraid, be very afraid
Not transitive
==/!= Compares values
does type coercion
===/!==
also compares types
'' == '0' // false0 == '' // true0 == '0' // true
© 2010 RoCk SOLiD KnOwledge Ltd.7
Truthyness and Falsyness
0, false, '', '0', null, undefined, NaN
all falsey
Everything else
truthy
© 2010 RoCk SOLiD KnOwledge Ltd.8
Control Statements
if..else
switch
for
while
do..while
with
© 2010 RoCk SOLiD KnOwledge Ltd.9
Functions
Many ways of declaring and calling functions
More later
© 2010 RoCk SOLiD KnOwledge Ltd.10
Exceptions
try..catch
throw
finally
© 2010 RoCk SOLiD KnOwledge Ltd.11
OO in JavaScript (Post ES6)
class keyword
constructors
inheritance
© 2010 RoCk SOLiD KnOwledge Ltd.12
ES6 Classes
class Person {constructor(name) {
this.name = name;}
printName () {console.log(this.name);
}}
© 2010 RoCk SOLiD KnOwledge Ltd.13
Inheritance
class User extends Person {constructor(name) {
super(name);}
printName () {super.printName();
}}
© 2010 RoCk SOLiD KnOwledge Ltd.14
OO in JavaScript (Pre ES6)
How to define objects in JavaScript
Prototypes
Inheritance
Instantiation
Sub-classing
© 2010 RoCk SOLiD KnOwledge Ltd.15
Prototypes
JavaScript supports prototypical inheritance
Each JavaScript functions have a 'prototype' property
Shared across instances
Can use to share functions
© 2010 RoCk SOLiD KnOwledge Ltd.16
Constructor functions
Can create objects many ways in JavaScript
Can use the object syntax
– var k = {name: 'Kevin'};
Can use the constructor syntax
function User(){};
var user = new User();
© 2010 RoCk SOLiD KnOwledge Ltd.17
Issues with instances
Creating instances creates multiple copies
Each instance gets its own copy of functions
function User(){this.name = function(){...}
};
var kevin = new User();kevin.name("Kevin");var terry = new User();terry.name("Terry");
© 2010 RoCk SOLiD KnOwledge Ltd.18
Inheritance
Prototypes also enable inheritance
Via the prototype chain
Can use instance of one object as prototype of another
© 2010 RoCk SOLiD KnOwledge Ltd.19
Inheritance
Set 'derived' prototype as 'base class'
Sometimes see User.prototype = new Person()
Now all derived instances share single base's properties
function Dummy () {}function Person() {
this.age = function (){...}}
function User() {this.name = function (name) {...}
}Dummy.prototype = Person.prototype;User.prototype = new Dummy();// otherwise User's ctor == PersonUser.prototype.constructor = User;
© 2010 RoCk SOLiD KnOwledge Ltd.20
Delegates
Enable lots of functional features
Functions as first class features in a language
Higher order functions
– Functions that take functions
– Functions that return functions
© 2010 RoCk SOLiD KnOwledge Ltd.21
Delegates
c# type
Can think of as a ‘function pointer’
delegate bool Predicate<T>(T value);
Predicate<int> IsAdult = x => x >= 18;
void DoIfAdult(Person p) {if(IsAdult(p.Age)) {}
}
© 2010 RoCk SOLiD KnOwledge Ltd.22
JavaScript Functions
JavaScript is more functional than OO based
Higher order functions
Closures
Arrow functions (ES6)
© 2010 RoCk SOLiD KnOwledge Ltd.23
Functions as first class objects
Functions
Can be assigned to variables
Passed to other functions
Returned from functions
© 2010 RoCk SOLiD KnOwledge Ltd.24
Assigning functions
One of the first things we'll do as a JavaScript programmer
function onStart(){}
window.onload = onStart;
// or
window.onload = function(){};
© 2010 RoCk SOLiD KnOwledge Ltd.25
Declaring functions
Declared using a function literal
function keyword
optional name
comma separated parameter list
body
© 2010 RoCk SOLiD KnOwledge Ltd.26
Examples of functions
function foo(){return true;}assert(typeof foo === "function", "defined");assert(foo.name === "foo", "named");
var bar = function(){return true;}assert(typeof bar === "function", "defined");assert(bar.name === "", "no name");
window.baz = function(){return true};assert(typeof baz === "function", "defined");assert(baz.name === "", "no name");
© 2010 RoCk SOLiD KnOwledge Ltd.27
Non global functions
Previous slide showed global functions
Scoped to 'window'
Functions can be scoped
function outer(){assert(typeof outer === "function", "function");assert(typeof inner === "function", "nested"); function inner(){}
}outer();assert(typeof inner === "undefined", "nested");
© 2010 RoCk SOLiD KnOwledge Ltd.28
JavaScript scoping
Scopes created by functions not blocks
i.e. {} does not create a scope
functions are hoisted to the top of the declaring block
function outer(){assert(typeof outer === "function", "function");assert(typeof inner === "function", "nested"); function inner(){}
}outer();assert(typeof inner === "undefined", "nested");
© 2010 RoCk SOLiD KnOwledge Ltd.29
Function parameters
A list of arguments can be provided when calling a function
these are assigned to the function parameters
numbers of arguments and parameters do not have to match
If fewer arguments than parameters
extra parameters are set to undefined
If more arguments than parameters
excess arguments are not assigned
© 2010 RoCk SOLiD KnOwledge Ltd.30
Implicit argument parameter
'this' and 'arguments' are also available inside the function
'arguments' is collection of all arguments passed
has .length property
access using array syntax
© 2010 RoCk SOLiD KnOwledge Ltd.31
'arguments' parameter
Not an array
is 'array like'
© 2010 RoCk SOLiD KnOwledge Ltd.32
Implicit 'this' parameter
Reference to the invoker of the function
Also known as the function context
'this' can vary depending on how the function is invoked
© 2010 RoCk SOLiD KnOwledge Ltd.33
'function' invocation
This is invocation as you would think of it
function createUser(){}createUser();
var updateUser = function(){};updateUser();
© 2010 RoCk SOLiD KnOwledge Ltd.34
'method' invocation
Function added as a property on an object
and called through that object
Inside the function 'this' is a reference to the calling object
var user;user.createUser = function(){};user.createUser();
function createUser(){ return this;}createUser(); // this === window
var user = {};user.createUser = createUser;user.createUser(); // this === user
© 2010 RoCk SOLiD KnOwledge Ltd.35
Closures
Closure defines a scope
Created when function is declared
Allows access to variables defined outside function
Variables can still be accessed when function is used
Even if their scope has disappeared
© 2010 RoCk SOLiD KnOwledge Ltd.36
Example
var outerValue = 'outer';
var inner;
test("closure tests", function () {function outerFunction() {
var innerValue = 'inner';assert(outerValue == "outer","ok");
function innerFunction(){assert(innerValue == "inner","ok");
}inner = innerFunction;
}outerFunction();inner(); // called but 'outerFunction' has
// long gone away});
© 2010 RoCk SOLiD KnOwledge Ltd.37
How Closures work
innerFunction is a closure
It captures the scope of where it was when it was declared
'closes over' the scope
outerFunction
innerFunction
outerValueinner
innerValue
© 2010 RoCk SOLiD KnOwledge Ltd.38
Using closures
Closures have many uses
Private variables
Binding 'this'
Event handlers
© 2010 RoCk SOLiD KnOwledge Ltd.39
Declaring private variables
Can define a constructor
Variables defined within are 'private' to the constructor
function User(name) {var _name = name;
this.getName = function () {return _name;
};}
var kevin = new User('kevin');
assert("kevin" == kevin.getName(), "Name is kevin");
© 2010 RoCk SOLiD KnOwledge Ltd.40
Arrow functions
Removes ceremony from anonymous functions
function displayMessage(displayer, message) {displayer.write(message);
}
displayMessage(function displayer(m) {console.log(m);
}, "Hello World");
displayMessage(m => console.log(m), "Hello, World");
© 2010 RoCk SOLiD KnOwledge Ltd.41
C#6 Iterators
Simple way of implementing IEnumerator/IEnumerable pair
IEnumerable<int> GetValue(){
for(int i = 0; i < 10; i++) yield return i;}
foreach(var i in GetValue()) Console.WriteLine(i);
© 2010 RoCk SOLiD KnOwledge Ltd.42
Generators and Iterators
Generators
function *foo() { var x = 1 + (yield "foo"); console.log(x);
}
var foo = foo();foo.next(); // {value: foo; done: false}foo.next(23); // {value: undefined; done: true}
© 2010 RoCk SOLiD KnOwledge Ltd.43
Iterators
function *foo() {yield 1;yield 2;yield 3;yield 4;yield 5;
}
var it = foo();var value = it.next();
for (var v of foo()) {console.log( v );
}
© 2010 RoCk SOLiD KnOwledge Ltd.44
Async
function getProfile() {var result = $.get();gen.next(result);
}
function getMeetings() {var result = $.get();gen.next(result);
}
function *getUserMeetings() {var a = yield getProfile();var b = yield getMeetings();console.log(a, b);
}
var gen = getUserMeetings();gen.next();
© 2010 RoCk SOLiD KnOwledge Ltd.45
Further Reading
Combining generators with promises
async/await in ES7 and TypeScript