preface

  • Online music poke me ah!
  • Music blog source code online!
  • Muddlehead in the front-end field bump bump for more than two years, want to see Vue source code, do not know if there is recently want to see the source of ape friends, if JS is not hard enough, suggest to re-learn JS with me, re-learn to believe that to see the source code, will get twice the result with half the effort.
  • Next we come to see JS object, function knowledge points can test what.

Interviewer: Why should we hire you? You’re hiring! Interviewer: Yes, but there are many applicants. Isn’t it your job to pick people? Interviewer: That makes sense

Start by asking yourself three interview questions

[‘ attribute name ‘] can be used to access data inside an object. When must [‘ attribute name ‘] be used?

How is a function called (executed)? Please give at least three examples.

How do I determine the value of this?

If you do, the interviewer is no match for you. If not, let’s first understand the concept of objects and functions. Only if you know the principle behind the problem, it will be easy to solve it.

Object object, so what is an object?

You think this is it?

Programmers want sweet love too?

Forget it. You’re a noble single ape.

Let’s get down to business.

Why have objects when you have variables to store data?

Because objects can manage multiple data uniformly. A variable can only hold one piece of data.

The characteristics of

  • object
    • An encapsulation of multiple data

    • A container used to hold multiple pieces of data

    • An object represents a thing in reality

composition

  • Attribute: Consists of the attribute name (string) and the attribute value (arbitrary)

  • Method: a special attribute (the attribute value is a function)

Look at the object structure below

var p = {
    name: 'o ze'.setName: function(name){
        this.name = name
    }
}
Copy the code

Isn’t the property name a string?

It doesn’t look like it either!

A: Programming is taking seemingly complex problems and making them simple

The attribute name is indeed a string, but the JS author feels that every time the attribute name needs to be quoted, so we can omit it for us.

Of course, you can use quotation marks by convention, and that’s fine.

In JSON, when we have to add attributes to an object, the attribute name must be quoted, or an error will be reported.

JSON authors are not as friendly as JS authors.

How do I access object internal data?

  • .(dot) Attribute name: Easy to encode, but sometimes unusable
  • [‘ attribute name ‘]: Cumbersome encoding, universal
var p = {
    name: 'o ze'.setName: function(name){
        this.name = name
    }
}

console.log(p.name, ".(dot) Attribute name")
console.log(p['age'].[' attribute name '])
Copy the code

Open the first interview question above.

Interviewer: You can use [‘ attribute name ‘] to access the internal data of an object. When must you use [‘ attribute name ‘]?

1. The attribute name contains special characters: – space

Requirement: Add a property to the p object: Content Type: text/jsonvar p = {}

// p.content-type = 'text/json'
p['content-type'] = 'text/json'
console.log(p['content-type'])  // 'text/json'
Copy the code

2. The attribute name is uncertain

var propName = 'myAge'
var value = 18

// p.propname = value // invalid
p[propName] = value
console.log(p[propName])  / / 18
Copy the code

Macabaca, what is a function?

concept

  • A package of n statements that implement a specific function
  • Only functions can be executed; other types of data cannot be executed

Why use a function?

  • Improved code reuse
  • Easy to read and communicate

How do you define a function?

  • Function declaration
  • expression
// Function declaration
function fn1 () { 
   console.log('fn1()')}/ / expression
var fn2 = function () { 
   console.log('fn2()')}Copy the code

Open the second interview question above.

Interviewer: How do you call (execute) a function? Please give at least three examples.

1. Direct call

function eat () { 
   console.log("Rich lady, Hungry hungry, soft rice, woo woo.")
}

eat()
Copy the code

2. Call by object

let obj = {
   eat: function (){
       log('Abba abba')
   }
}

obj.eat()
Copy the code

3. The new call

function eat () { 
   console.log('Nice guy, give it a thumbs up.')}let e = new eat()
Copy the code

4. Call/apply calls

var obj = {}
function kiss () {
   this.you = 'o ze'
}

// Requirement: I want to execute kiss in obj object. How do I do that?

obj.kiss()  // Cannot be called directlyAre you kidding me? Kiss functions are not even in OBj. So what? We can use call/apply instead. kiss.call(obj)// Print 'azer'Equivalent to the obj.kiss() call, JS is very powerful, and call allows a function to be called as a method specifying any object.Copy the code

Kiss. call(obj) means that kiss is executed inside an obj object.

Ok, if you want an answer, you print obj. You on the console and see if it prints’ AZz ‘.

Kiss.call /apply(obj): Temporarily call KISS as a method of OBj.

A callback, a special function, right?

A callback function must satisfy the following three conditions

  • You define
  • You didn’t call
  • But eventually it did (at some point or under some condition)
<button id="btn"Word-wrap: break-word! Important; "> </button>document.getElementById('btn').onclick = function () { 
   alert(this.innerHTML)
}

// You defined it, but you didn't call it
function () { 
   alert(this.innerhtml)} but when I click the button BTN, the function executes.Copy the code

Common callback functions?

1. The DOM event callback function ==> the DOM element where the event occurred

document.getElementById('btn').onclick = function () { 
   alert(this.innerHTML)
}
Copy the code

2. Timer callback ===>window

// Timer: timeout timer, cycle timer

setTimeout(function () { // Timer callback function
   alert('Here I go again. I know what I know.')},2000)
Copy the code

3. Ajax request callback function

axios.then(res= >{
    console.log(res)
}).catch(err= >{
    console.log(err)
})
Copy the code

4. Lifecycle callback functions

// For example, vue creates the Create lifecycle

new Vue({
    data(){},
    create(){
        console.log('Created')}})Copy the code

Anonymous function, which is a special function, right?

Full name: immediate-invoked Function Expression, also called: Immediate Function.

Ordinary functions don’t satisfy you? Why anonymous functions? What’s the use?

  • Hide the implementation
  • Does not pollute the external (global) namespace
  • Use it to encode JS modules
(function () { // The anonymous function calls itself
    var a = 3
    console.log(a + 3)
})()

// Print 6 directly, do not need to be called, execute yourself
// the a variable is a local variable and does not pollute the global space
Copy the code

Extension: remember the JQ era, read the source code, useful to anonymous function, there is probably this way to write.

var a = 4
console.log(a) ; (function () {
    function load () {
      console.log('Add an event handler to the Load event')}window$=function () { // Expose a global function
      return {
        load: load
      }
    }
})()
Copy the code

One thing I want to say is why anonymous functions are preceded by semicolons;

Suppose: Without the semicolon, the program ends up compiling like this:

var a = 4
console.log(a)(function () {... }Copy the code

Uncaught TypeError: console.log(…) TypeError: console.log(…) is not a function

According to?

That’s because anonymous functions start with parentheses (). For programs that use parentheses () to represent function execution, the function name should be there. , naturally reporting an error.

This is why JS statements are followed by semicolons.

What if I don’t want to add a semicolon after every statement (console.log(a))?

He swore in front of his girlfriend not to put a semicolon after the sentence.

You need to prefix the anonymous function with a semicolon, or if you don’t.

See why anonymous functions are preceded by a semicolon!

Who are you pointing at? this

concept

  • Any function is essentially called from an object, and if it is not specified directly it is a window

  • All functions have a variable this inside them

  • Its value is the current object on which the function is called

Last interview question above.

Interviewer: How do you determine the value of this?

1. (with function call, this as window) Global call Fun(): window

function Fun(color) {
   this.color = color  // This refers to Fun, this.color adds the property to Fun
}

Fun('pink'); // Who is this here? Is the window. In a global environment, window if not specified directly.
Copy the code

2. (when called as a constructor, this is the newly created object) to new Kiss(): the newly created object

function Kiss() {}

var kiss = new Kiss(); // Who is this here? Is a kiss.

// This is the same as new Class().
Copy the code

Kiss.getcolor (): kiss

function Kiss() {
   this.color = color;
   this.getColor = function(){
       return this.color
   }
}

var kiss = new Kiss('red'); 
kiss.getColor();  // Who is this here? Is a kiss.

// The kiss object calls getColor, so this is the object.
Copy the code

4. (Call specifies this in the function with the first argument) kiss.call(obj): obj

function Kiss() {
   this.color = color;
   this.setColor = function(color){
        this.color = color 
   }
}

var kiss = new Kiss('red');

var obj = {};
kiss.setColor.call(obj, "black"); // Who is this here? Is the obj.

When the kiss object calls another object obj, this refers to another object obj.
Copy the code

It looks like you can do this. One more?

function fun1() {
   function fun2() {
     console.log(this);
   }

   fun2(); // Who is this? Leave a post in the comment section
}

fun1();
Copy the code

The last

A raise, and finally a monthly income of ten thousand people.Copy the code

In the past to recommend

Lao Shi said that everything is the object, you also believe?

Vue-cli3 builds the component library

Vue implements dynamic routing (and the interviewer blows project highlights)

Axios manipulation in a project you didn’t know about (Core principles of handwriting, compatibility)

VuePress builds project component documentation

Vue koa2 + + nginx deployment

Vue-typescript-admin-template background management system

The original link

Juejin. Cn/post / 700017…