天天看點

FCC-Object Oriented and Functional Programming

在Basic JavaScript當中我們學習了JS最基本的文法,對于已經有過Java背景的同學來說,應該沒有什麼不能接受的地方,唯獨JS的資料結構比較松散,自由罷了。接下來學一些面向對象的JS基本以及一些JS中數組的函數和String的函數。

1. 建立對象的時候除了字面量表示法,還可以:We are also able to create objects using constructor functions. A constructor function is given a capitalized name to make it clear that it is a constructor. Here’s an example of a constructor function:

```
var Car = function() {
  this.wheels = 4;
  this.engines = 1;
  this.seats = 5;
};
var myCar = new Car();
// Note that it is important to use the new keyword when calling a constructor. This is how Javascript knows to create a new object and that all the references to this inside the constructor should be referring to this new object.
```
           

2. We used the this keyword to reference public properties of the current object. We can also create private properties and private methods, which aren’t accessible from outside the object. To do this, we create the variable inside the constructor using the

var

keyword we’re familiar with, instead of creating it as a property of this.

3. The

map

method will iterate through every element of the array, creating a new array with values that have been modified by the callback function, and return it. Note that it does not modify the original array.

4.

filter

is passed a callback function which takes the current value (we’ve called that val) as an argument.Any array element for which the callback returns true will be kept and elements that return false will be filtered out.

5. You can use the method

sort

to easily sort the values in an array alphabetically or numerically. Sort can be passed a compare function as a callback. The compare function should return a negative number if a should be before b, a positive number if a should be after b, or 0 if they are equal. If no compare (callback) function is passed in, it will convert the values to strings and sort alphabetically.

6. You can use the reverse method to reverse the elements of an array.

reverse

is another array method that alters the array in place, but it also returns the reversed array.

7. We can split a String into an arrayor join elements in an array into a String.

繼續閱讀