Author: milter
Blog: https://www.jianshu.com/p/1b1b1110708d
preface
React Native’s rise seems to confirm the old adage: “Everything that can be implemented in JavaScript will eventually be implemented in JavaScript!” In order not to be abandoned by The Times, I used Java for a long time, concentrated on learning JavaScript for 5 days, the result is: I love JavaScript! Everything you feel uncomfortable about in Java is gone, blue sky, blue sea, blue sea, what a big green grassland! The following is a record of my learning process, hoping to be helpful to the majority of Androiders preparing to learn React Native. The article will explain my specific learning path at the end, feel good points like ha! Note: The JavaScript described in this article is based on the latest ES6.
As a Javaer for many years, the way I learn JavaScript is to learn by comparison, trying to identify the similarities and differences between Java and JavaScript, deepen understanding in comparison, and finally achieve the purpose of learning JavaScript.
Many programming languages have their own taglines. Java’s is: “Write once, Run everywhere!” Similarly, JavaScript has its own tagline, “Everything is Object!” My learning also started with this sentence, for which I need to clarify the following questions:
-
What exactly is an object in JavaScript?
-
In JavaScript, is the base data type an object?
-
Is an array an object in JavaScript?
-
Are functions objects in JavaScript?
-
Can objects inherit in JavaScript?
-
How many methods are there to create objects in JavaScript?
-
How do you use special objects like functions in JavaScript? After figuring out the above questions, I explored the following questions:
-
What is a closure in JavaScript?
-
Do variables have scope in JavaScript?
-
What wizardry does JavaScript have that Java doesn’t?
After learning React Native, there won’t be any language difficulties. I’m really happy! Finally have fun with React Native!
What exactly is an object in JavaScript?
In a nutshell, in JavaScript, an object is just a Map with key-value pairs and nothing else!
1. Create an object
Let’s create an object:
var person = new Object();
Copy the code
Familiar new appeared, very friendly. Var is a new thing. Let’s see what it is.
To declare a variable in Java, we must specify its type, as follows:
Person to Person; The Dog Dog; The Cat Cat;
Copy the code
We must specify the type of the variable because Java is a statically typed language and the compiler will not be able to understand the variable we declare without it. In contrast to Java, JavaScript is a dynamically typed language. When you declare a variable, you don’t need to specify the type of the variable, just use the var keyword. The variable can be of any type, and JavaScript dynamically verifies the type of the variable only when you use it.
2. Add attributes
In the key-value pairs that an object contains, the keys are called the properties of the object, and the values are called the corresponding property values. All keys are strings, and values can be of any type.
Let’s add two attributes to the above object:
person['name'] = 'milter'; person['age'] = 31;
Copy the code
One of the things that’s new here is that in JavaScript, both single and double quotes can be used to create strings, they’re the same thing. Now we can access these attribute values:
var name = person['name'] ; // miltervar age = person['age'] ; / / 31
Copy the code
3. Simple method
The above methods of creating objects, adding attributes, and accessing attributes are clumsy:
-
Syntax inflexible for adding and accessing properties (frequent typing of [] and ‘ ‘)
-
You can only add one attribute at a time
To get around the clumsiness of creating objects and adding attributes, JavaScript provides a curly brace ({}) syntax for creating objects:
var person = {'name' : 'milter', 'age': 31 };
Copy the code
In this way, multiple attributes can be assigned to an object while it is being created.
The problem is not solved yet. You need to write single quotes to assign attributes above, and parentheses and single quotes to access attributes above.
To do this, JavaScript further states that if the string representing the attribute complies with JavaScript’s naming conventions for identifiers, the single quotation marks around the string can be omitted and the attribute can be accessed using the Object.prop syntax.
JavaScript naming conventions for identifiers are as follows:
-
Case sensitive, Myname and Myname are two different identifiers.
-
The first character of an identifier can start with an underscore (_), dollar ($), or a letter, not a number.
-
Other characters in the identifier can be underscore (_), dollar ($), letters, or numbers.
-
Keywords and reserved words cannot be used as identifiers.
Obviously, our name and age properties conform to this specification, so now we can write:
var person ={ name : 'milter', age: 31 }; var name = person.name ; // miltervar age = person.age ; / / 31
Copy the code
Even cooler, we can continue to add or remove attributes to the object after it has been created, as follows:
person.sex = 'man' ;
Copy the code
This adds the property called sex to the person object, whose value is the string ‘man’.
delete person.sex ;
Copy the code
This removes the sex property from the object person.
You might be tempted to ask, are methods in objects also properties, key-value pairs? And the answer is YES, and we’ll talk more about that when we talk about functions, so for now.
In JavaScript, is the base data type an object?
There are six basic data types in JavaScript:
-
String
-
Number
-
Boolean
-
Symbol
-
undefined
-
null
String and Boolean are essentially the same as Java. The way to get a String value, as mentioned above, is to enclose a String in single or double quotation marks. Boolean has only two values: true and false. Number can only be a double-precision floating-point Number, which is a Java double. Symbol is a new type, introduced in ES6. Each value is unique, and the syntax for obtaining a Symbol value is Symbol(String).
Such as:
var symb1 = Symbol('one'); var symb2 = Symbol('one'); var symb3 = Symbol(); var symb4 = Symbol();
Copy the code
String is optional. You can use this syntax to obtain a Symbol value with or without String. String just adds a description to the Symbol value. The value of the Symbol is unique, meaning that you cannot obtain the same Symbol value twice (just as it is impossible to step into the same river twice, please call me philosopher). For example, with a data type like Number, I can take the value 1 over and over again and assign it to different variables:
var number1 = 1 ; var number2 = 1 ;
Copy the code
Number1 and number2 are equal, and String and Boolean can do the same. But Symbol is not like that! Above, SymB1! = symb2, symb3! = symb4.
If you want to add a new in front of Symbol, do not do this. JavaScript does not allow this.
Keep in mind that no object is being created, just a unique value. Symbol looks a lot like the UUID in Java; Symbol() is equivalent to uuID.randomuuid (). Both data types, undefined and null, have only one value, which is the name of their type. Undefined is used to indicate that the variable is not initialized, and null is used to indicate that the object is empty.
Going back to the question in this section, is the base data type an object?
The answer is NO!
They are not objects for two reasons:
-
They are immutable. After you create a Person object, you can continue to add and remove properties to it, as well as change the values of the original properties. Basic data types have only one value, and they have no properties that can be modified or added or deleted. And once you get a value, it’s impossible to change it. This is much like the immutability of Strings in Java.
-
They are both compared and passed on a value basis, and objects are compared and passed on a reference basis. Such as:
var a = 'one' ; var b = 'one'; var c = {one:1}; var d = {one:1}; var e = c ;
Copy the code
Above, a and B are equal because two variables have the same value, c and D are not equal because two variables refer to two different objects, but E and C are equal because they both refer to the same object. If you do this: e.on = 2; Then you will find that C. one will also become two.
Just as Java has wrapper classes for primitive data types (Integer and int, Double and Double, and so on) that can be automatically unboxed, JavaScript has a similar mechanism, implemented more thoroughly.
Looking back at the six basic data types, the first four are uppercase because JavaScript created wrapper objects for them, and the last two, undefined and NULL, are lowercase because JavaScript didn’t provide wrapper objects for them. Take String as an example:
var str = new String('one');
Copy the code
The String ‘one’ is used to create a String object STR, which has a number of String manipulation methods you can call. Similarly with Number and Boolean, you can:
Var num = new Number(3.1415); var bool = new Boolean(true) ;
Copy the code
You can use typeof syntax to verify that they are not objects.
typeof bool //objecttypeof num //objecttypeof str //object
Copy the code
The exception is Symbol. You cannot use the new syntax to create a Symbol wrapper object. JavaScript discouragesvery much from wrapping symbols into objects. If you specifically want to wrap a Symbol value as an object, you can only do this:
var sym = Symbol(); var wrapSymbol = new Object(sym);
Copy the code
Similarly, JavaScript has a similar mechanism and is much more flexible than Java’s auto-unboxing. In short, when you use basic data as an object, it automatically becomes an object (except undefined and null, for reasons explained above). Examples are as follows:
var hello ='hello'; var str = hello.slice(1); // STR is 'ello'
Copy the code
This is more convenient than Java!
The principle is as follows: JavaScript finds that we have made a slice method call to the primitive datatype Hello. It creates a temporary wrapper object with the value of Hello, new String(Hello), and then calls Slice (1) on this wrapper object, returning the primitive datatype String ‘ello’. The temporary wrapper object is then destroyed.
Is an array an object in JavaScript?
Basic data types are not objects, and JavaScript’s tagline is self-defeating. Now let’s move on to arrays. Answer first: Arrays are objects!
In JavaScript, you can define an array like this:
var arr = [ 'one', 'two', 'three' ];
Copy the code
At first glance, there may seem to be no key-value pairs, but JavaScript converts the above code to something like this:
var arr = { '0':'one', '1':'two', '2':'three' } ;
Copy the code
We know that arrays belong to objects.
It’s a little bit more intuitive to write it the first way, and you can think of it as a syntactic sugar for defining an array. Now, let’s access the elements in the array. Based on what you’ve learned about objects, it seems that the array elements should be accessed like this: arr.0, arr.1, arr.2
The truth is, it’s not allowed! Why is that?
As mentioned earlier, object syntax (Object.prop) can only be used to access an object’s properties if the property string complies with JavaScript’s naming conventions for identifiers. In the array above, the attribute strings are ‘0’,’1′, and ‘2’, all of which are numeric strings that do not comply with the naming conventions for identifiers, so we cannot use dot syntax to access elements in the array.
How do you access it? Use the basic method of accessing object properties as follows:
arr[‘0’], arr[‘1’], arr[‘2’]
Because arrays are used so often that it would be too tedious to write single quotes every time the user accesses an array element, JavaScript has optimized the array object so that you can write arr[0], arr[1], arr[2] without single quotes.
The principle of optimization is very simple: behind the scenes, JavaScript automatically quotes the east and west sides of the brackets.
But this creates a very subtle problem. If we write: arr[01], JavaScript will convert it to: arr[’01’].
Obviously, the object arR does not have the attribute ’01’, because the strings ‘1’ and ’01’ are not equal. To avoid this error, JavaScript disallows entering a Number starting with 0 when accessing an array. It will display an “Invalid Number” error and prompt you to change it.
In addition, JavaScript array objects have a length property, which is very confusing, as shown in the following code:
var arr = ['one', ,'three'];
Copy the code
In this array, only we initialize two elements, and we leave the second element blank. In Java, this is not allowed, that is, you cannot initialize an array like this:
Int [] arr = {1, 2}
Copy the code
JavaScript converts the above code to something like this:
var arr = {'0':'one','1':undefined,'2':'three'};
Copy the code
If you test arr[1] == undefined, you will get true. Arr. Length is still 3. Strictly speaking, arr.length is equal to the index of the last element plus 1.
Are functions objects in JavaScript?
In JavaScript, functions first take on the properties of Java methods, which take input, operate on it, and produce output as needed. Again, answer first: functions are objects!
1. Definition of functions
In JavaScript, there are two ways to define a function: declaratively and expressively.
-
Way to declare:
function foo1(){ return a+b ; };
Copy the code
-
The form of the expression:
var foo2 = function (a,b) { return a + b; };
Copy the code
The first method defines a function named foo1 and the second method defines a function named foo2. What is the difference? The main difference is availability.
If foo1 and foo2 exist in the same JS file, the js engine scans the entire file to find and load foo1. The execution is then interpreted statement by statement, and any calls to foo1 that occur anywhere in the file (either before or after foo1 is defined) will be handled correctly because the JS engine has loaded the function ahead of time. Foo2 will only be loaded when it is executed on the line where it is defined, and will only be called in subsequent statements. If you use foo2 before defining the line where it is defined, the program will report an error. In short, declaratively defined functions are loaded before the program executes and can be used anywhere in the program file. A function defined as an expression is loaded only when it is executed on the line where the function is defined, and can only be used in subsequent statements.
Here’s the problem: look at the following way to define a function:
var foo2 = function foo3(a,b) { return a + b; };
Copy the code
Yi! What the hell is this? What kind of function definition is it? Is the name of this function foo2 or foo3? Why this weird way of defining functions?
In short, it belongs to a function defined in the manner of an expression. The name of the function is foo2, and the sole purpose of foo3 is to use that function inside it (to achieve recursion). Foo3 makes no sense anywhere else in the program, and at this point you can think of foo3’s scope as inside that function.
Now you can explain the object method problem. The method of an object is also a property, in which case the name of the property is the name of the function, and the value of the property is a function. Examples are as follows:
var obj = { add: function(a,b){ return a+b; }};
Copy the code
In the above code, the object obj has a property add, and its value is a function whose name is the property’s name add, so you can use obj like this:
Var result = obj. Add (4, 9); // result == 13
Copy the code
The above way of defining functions is expressed, that is, the Add function is not loaded until the object is created. Objects can also use declaratively defined functions as attribute values, as follows:
var obj = { }; obj.add1 = add ; function add(a,b){ return a+b; };
Copy the code
In the above code, we assign the declaratively defined function add to a property named add1 in obj, so you can use it like this:
Var result = obj. Add1 (4, 9); //result == 13
Copy the code
So the question is, what is the relationship between add1 and add? Are they just two names for a function? The answer is: NO! This involves another concept of functions, scope, which I’ll talk about later, but for the moment.
By understanding that object methods are also key-value pairs, we can understand the statement at the beginning of this article more thoroughly: in JavaScript, an object is a Map with key-value pairs and nothing else!
Now that we know how functions are defined and that object methods are key-value pairs, let’s look at the topic of this section: Functions are objects too! Let’s take the above functions foo1(declaratively defined) and foo2(expressively defined) as examples.
The most obvious proof that functions are objects is that we can add, delete, and modify attributes to them. As follows:
-
Added property: foo1.prop1 = ‘first prop’; foo1.prop2 = ‘second prop’;
-
Change properties: foo1.prop1 = ‘changed Prop ‘; foo2.prop1 = ‘changed prop’;
-
Delete property: delete foo1.prop1; delete foo2.prop1;
In fact, we can think of a function as a special object that can be called (an object which can be called!). . Apart from this particularity, functions are not much different from ordinary objects.
summary
Now that we have solved the first four of the 10 questions posed at the beginning of this article, we have a very thorough understanding of the JavaScript tagline: “Everything is object.” We learned the following:
-
An object is nothing but a collection of key-value pairs.
-
JavaScript has six basic data types, and they are not objects!
-
Arrays are objects, although they don’t look like objects at first glance.
-
Functions are also objects, but in a special way, objects that can be called.
The original purpose of this series was to provide a targeted and concise JavaScript quick start tutorial for Android developers learning React Native. By default, everyone is familiar with Java. Therefore, the similarities between JavaScript and Java are not covered, such as for, while, if statements, and so on, but focus on the obvious difference between JavaScript and Java content, while trying to write from the perspective of Java and JavaScript comparison. The purpose is to make it easy for you to understand.
In addition, as it is preparing for React Native learning, content related to webpage processing in JavaScript is also avoided as much as possible.
-
Visible data structures – Do you really know anything about array tables?
-
CSS font icon to know how much
-
This is probably the best RxJava 2.x Tutorial ever (part 2)
Wait, don’t go yet! Code egg is on the move again! Participate in the activity can not only develop their own good habits, but also get “code egg” IP series exclusive prizes, speed up…
Poke me for details
Question of the day:
What features of JavaScript do you like?
Message format:
Punch x days, answer: XXX.
Here’s a trick:
In just 3 steps, you won’t miss a single article!