DAY20 brush interview questions

JS method for creating objects

1) new an instance of an Object
Instantiate an Object, add properties and methods to it, and save the instance in the variable person

var person = new Object();
person.name="zj";
person.age=20;
person.say = function(){
	alert("hi")
}

2) Object literal mode

var person = {
	name:"zj";
	age:"20";
	say : function(){
		alert(this.name);
	}
}

The first two methods use the same interface to create many objects, which will produce a lot of duplicate code

3) Factory mode

function createPerson(name,age,jpb){
	var p = new Object();
	p.name = name;
	p.age = age;
	p.job = job;
	p.say = function(){
		alter(this.name);
	}
	return p;
}
var p1 = createPerson('NCT',18,'singer');
var p2 = createPerson('RV',22,'dancer');

It solves the problem of creating objects one by one, but does not solve the problem of Object recognition (how to know the type of an Object). All returned objects are Object types.

4) Constructor mode

function Person(name,age,jpb){//Constructors start with uppercase in order to separate functions; The constructor itself is also a function, but it can create objects.
	this.name = name;
	this.age = age;
	this.jpb = jpb;
	this.say = function(){
		alert(this.name)
	}
}
var person1 =new Person('NCT',18,'singer');
var person2 =new Person('RV',22,'dancer');

Compare the differences between factory modes:

  • Create objects without displaying
  • Attributes and methods are directly assigned to this object
  • There is no return statement
  • You can identify the type of object and use the instanceof operator

alert(person1 instanceof Object);//ture
alert(person1 instanceof Person);//ture
alert(person2 instanceof Object);//ture
alert(person2 instanceof Object);//ture

Disadvantages:
Each method must be recreated on each instance. A method refers to a function defined in an object. If there are a large number of methods, it will occupy a lot of unnecessary memory.

5) Prototype creation object pattern

function Person() {
}

Person.prototype.name = "lisi";
Person.prototype.age = 21;
Person.prototype.family = ["lida","lier","wangwu"];
Person.prototype.say = function(){
    alert(this.name);
};
console.log(Person.prototype);   //Object{name: 'lisi', age: 21, family: Array[3]} 

var person1 = new Person();        //Create an instance of person1
console.log(person1.name);        //lisi -- from prototype

var person2 = new Person();        //Create instance person2
person2.name = "wangwu";
person2.family = ["lida","lier","lisi"];
console.log(person2);            //Person {name: "wangwu", family: Array[3]} -- from instance
// console.log(person2.prototype.name);         // report errors
console.log(person2.age);              //21
function Person(){}
Person.prototype.name = 'Nike';
Person.prototype.age = 20;
Person.prototype.jbo = 'teacher';
Person.prototype.sayName = function(){
 alert(this.name);
};
var person1 = new Person();
var person2 = new Person();
person1.name ='Greg';
alert(person1.name); //'Greg' - from instance
alert(person2.name); //'Nike' - from prototype

All object instances share its properties and methods
When adding a property to an object instance, this property will mask the property with the same name saved in the prototype object.

6) Combining constructors and prototype patterns
The constructor pattern is used to define instance properties, and the prototype pattern is used to define methods and shared properties.

function Person(name,age,job){
 this.name =name;
 this.age = age;
 this.job = job;
}
Person.prototype = {
 constructor:Person,
 sayName: function(){
 alert(this.name);
 };
}
var person1 = new Person('Nike',20,'teacher');

The composite pattern shares references to the same method, which also ensures that each instance has its own private properties, saving memory to the greatest extent.

What data types does JS have

Basic data types: Null, Undefined, String, Number, Boolean, Object, Symbol, BigInt (newly added in ES6)
Symbol: represents a unique and immutable data type after creation. It is mainly used to solve all possible variable conflicts.
BigInt: data of numeric type, representing an integer in any precision format. You can also exceed the safe Number range represented by Number.

Reference data types: Object, Array, Date, Function, RegExp

Stack: raw data type
Heap: reference data types (objects, data, functions)

JS data type judgment method

1)typeof
Among them, array, object and null will be judged as object, and other judgments are correct

console.log(typeof 2);               // number
console.log(typeof true);            // boolean
console.log(typeof 'str');           // string
console.log(typeof []);              // object    
console.log(typeof function(){});    // function
console.log(typeof {});              // object
console.log(typeof undefined);       // undefined
console.log(typeof null);            // object

2)instanceof
It can correctly judge the reference data type of the object, but not the basic data type. Its internal operation mechanism is to judge whether the prototype of this type can be found in its prototype chain.

console.log(2 instanceof Number);                    // false
console.log(true instanceof Boolean);                // false 
console.log('str' instanceof String);                // false 
 
console.log([] instanceof Array);                    // true
console.log(function(){} instanceof Function);       // true
console.log({} instanceof Object);                   // true

3)constructor

console.log((2).constructor === Number); // true
console.log((true).constructor === Boolean); // true
console.log(('str').constructor === String); // true
console.log(([]).constructor === Array); // true
console.log((function() {}).constructor === Function); // true
console.log(({}).constructor === Object); // true

If you create an object and change its prototype, the constructor cannot be used to determine the data type.

function Fn(){};
 
Fn.prototype = new Array();
 
var f = new Fn();
 
console.log(f.constructor===Fn);    // false
console.log(f.constructor===Array); // true

4)Object.protype.toString.call()
Use the prototype method toString of Object object to judge the data type

console.log(Object.prototype.toString.call(undefined)); // "[object Undefined]" 
console.log(Object.prototype.toString.call(null)); // "[object Null]" 
console.log(Object.prototype.toString.call(123)); // "[object Number]" 
console.log(Object.prototype.toString.call("abc")); // "[object String]" 
console.log(Object.prototype.toString.call(true)); // "[object Boolean]"

function fn() {
  console.log("ming");
}
var date = new Date();
var arr = [1, 2, 3];
var reg = /[hbc]at/gi;
console.log(Object.prototype.toString.call(fn));// "[object Function]" 
console.log(Object.prototype.toString.call(date));// "[object Date]" 
console.log(Object.prototype.toString.call(arr)); // "[object Array]"
console.log(Object.prototype.toString.call(reg));// "[object RegExp]"

The toString method is also called by the detection object obj. The result of obj.toString() is different from that of Object.prototype.toString.call(obj). Why?

This is because toString is the prototype method of Object, and types such as Array and function, as instances of Object, override the toString method. When different Object types call the toString method, according to the knowledge of the prototype chain, they call the corresponding rewritten toString method (the function type returns the string with the content of the function body, and the Array type returns the string composed of elements...), instead of calling the prototype toString method on the Object (returns the specific type of the Object), so obj.toString() is used You can't get its Object type, you can only convert obj to string type; Therefore, when you want to get the specific type of the Object, you should call the toString method on the Object prototype.

Implementation principle and implementation of instanceof operator

The instanceof operator is used to determine whether the prototype attribute of the constructor appears anywhere in the prototype chain of the object.

function myInstanceof(left´╝îright){
	//Gets the prototype of the object
	let proto = Object.getPrototype(left)
	//Gets the prototype object of the constructor
	let prototype = right.prototype;

	//Judge whether the prototype object of the constructor is on the prototype chain
	while(true){
		if( !proto )
		return false;
		if( proto === prototype )
		return true;
		//If it is not found, continue to find the prototype, and use the Object.getPrototypeOf method to get the prototype of the specified object
		proto = Object.getPrototype(proto);
	}
}

What are the updates to HTML5

1) Semantic label

  • Header: defines the page (header) of the document
  • nav: defines the part of the navigation link
  • Footer: defines the footer (bottom) of a document or section
  • Article: defines the content of the article
  • Section: defines a section in a document
  • aside: defines the content (side) other than the content in which it is located
    2) Media label
  • audio: audio
  • video: video
  • Source: specify the video source in video
    3) Form
    form types
  • Email: verify whether the email address is legal
  • URL: validate URL
  • number: you can only enter numbers. You can set the default value of max/min/value
  • search: a small cross will be provided after the input box to delete the input content
  • Color: provides a color picker
  • time: hour, minute and second
  • data: Date: select mm / DD / yy
  • datatime: time and date (currently only supported by safari)
  • DataTime local: date time control

Form properties:

  • placeholder: prompt information
  • autofocus: get focus automatically
  • autocomplete = "on" or "off" use premise (the form must have been submitted and must have a name attribute)
  • required: the input box must not be empty and can only be submitted if there is a value.
  • Pattern = "" write the desired regular pattern, such as mobile phone number "^ (+ 86)?\d{10} $"
  • Multiple: you can select multiple files or mailboxes
  • Form = "from form ID"

Form events:

  • oninput: this event will be triggered whenever the content of the input box in input changes
  • oninvalid: this event is triggered when the verification fails

4) DOM query operation

  • document.querySelector()
  • document.querySelectorAll()

The objects they select can be labels, classes (you need to add dots), and IDS (you need to add #)

5) web storage
localStorage,sessionStorage

What are the new features in CSS3

frame:
Border radius: add rounded borders
Border shadow: add shadow to the box (horizontal displacement, vertical displacement, blur radius, shadow size, shadow color, insetr [inner / outer shadow])
Border image: sets the border image
Bode image source: the path of the border picture
Border image repeat: whether the image border is tiled (repeat tiled round stretch stretch)
Background:
Background size: background picture size
Background origin: specifies where the background position attribute is positioned relative to.
Background clip: Specifies the drawing area of the background (padding box, border box, content box)
Gradient:
Linear break: defines how to wrap lines
Word wrap: allows long content to wrap automatically
Text overflow: what should I do when a text overflow contains its element
Text shadow: text shadow (horizontal displacement, vertical displacement, blur radius, shadow color)
transformation:
transform is applied to 2D3D transformation, which can rotate and move elements
Zoom, tilt
Transform origin: you can change the position of element transformation (xyz axis)
Transform style: specifies how nested elements are rendered in a three bit space
2D conversion method:
Rotate rotate translate (x, y) specifies the displacement of the element in two-dimensional space, and scale(n) defines the scale conversion
3D conversion method:
perspective(n) translate rotate scale for 3D
Transition:
Transition property name
Transition duration: the time it takes to complete the transition effect
Transition timing function: Specifies the speed of the switching effect
Transition delay: specifies when to start switching effects
Animation:
Animation name is the @ keyframes animation name
Animation duration time required for animation
Animation timing function animation how to complete a cycle
Animation delay the delay interval before the animation starts
Animation iteration count animation playback times
Does the animation direction play the animation backwards in turn

vue life cycle

beforeCreate
created
beforeMount
mounted
beforeUpdate
updated
beforeDestroy
destroyed

vue component value transfer

Father to son
The parent component needs to bind the data: name = value
Subcomponents receive through props

Son to father
Sub components pass custom events through $emit
Parent component receive

Brother pass value
Public event bus
$emit custom event
$on to receive

Fundamentals of Vue

When a Vue instance is created, the Vue will traverse the properties in the data, convert them into getters / setters with Object.defineProperty (vue3 uses proxy), track relevant dependencies internally, and notify changes when properties are accessed and modified. Each component instance uses a corresponding watcher program instance. It will record the properties as dependencies during component rendering, and then notify the watcher to recalculate when the setter of dependencies is called, so that its associated components can be updated.

The difference between MVC and MVVM

MVC
MVC organizes the code structure by separating Model, view and Controller. View is responsible for the page display logic, and Model is responsible for storing the business data of the page and the corresponding data operations. View and Model apply observer mode. When the Model layer changes, it will notify the relevant view layer to update the page. The Controller layer is the link between the view and the Model, and is mainly responsible for the response operation between the user and the application. When the user interacts with the page, the event trigger in the Controller starts to work. The Model layer is called to complete the modification of the Model, and then the Model layer notifies the view layer of the update.
MVVM
Model represents the data model, and data and business logic are defined in the model layer
View represents UI view and is responsible for displaying data
ViewModel is responsible for monitoring data changes in the Model, controlling view updates, and handling user interactions.

Model and View are not directly related, but are connected through ViewModel. There is a two-way data binding relationship between model and ViewModel. Therefore, when the data in the model changes, the refresh of the View layer will be triggered, and the data changed due to user interaction in the View will also be synchronized in the Mode.
This mode realizes the automatic synchronization of data between Model and View, so developers only need to focus on the maintenance of data, rather than operating the DOM themselves

The difference between computed and Watch

Computed attribute: it does not support asynchrony. It depends on other attribute values, and the computed value is cached. The computed value will be recalculated the next time the computed value is obtained only if the dependent attribute value changes.
watch listener: it supports asynchrony, more observation and no caching. It is similar to the monitoring callback of some data. Whenever the monitored data changes, the callback will be executed for subsequent operations.

The difference between computed and methods

computed is based on cache. If the calculated attributes are not transformed, they will not be recalculated, and the cached data will be executed.
methods are not cached, that is, the method will be executed as long as it is called.

The difference between v-if and v-show

  • v-if dynamically adds or deletes DOM elements to the DOM tree; v-show controls display or hiding by setting the display style attribute of DOM elements.
  • v-if switching has a local compilation / unloading process. In the switching process, the internal event monitoring and sub components are properly destroyed and reconstructed; v-show is just a simple css based switch.
  • Compilation condition: v-if is inert. If the initial condition is false, nothing will be done. It will be compiled only when the condition is true for the first time; v-show is compiled under any condition, true or false, any is cached, and DOM elements are retained.
  • v-if has higher switching consumption; v-show has higher initial rendering consumption.
  • v-if is suitable for operation conditions and is unlikely to change; v-show is suitable for frequent switching.

Why is data a function rather than an object?

Objects in JS are data of reference type. When multiple instances reference the same object, as long as one instance operates on the object, the data in other instances will also change.
In vue, if you want to reuse components, you need each component to have its own data, so that components will not interfere with each other.
Therefore, the data of components cannot be written in the form of objects, but in the form of functions. Data is defined in the form of function return value, so that when reusing components each time, a new data will be returned. Each group price will have its own private data space, maintain its own data, and will not interfere with the normal operation of other components.

How to implement lazy loading of Vue router

Non lazy loading:

import List from '@/components/list.vue'
const router = new vueRouter({
	routes:[{
		path:'/list',
		component:List
	}]
})

1) Method 1: use the arrow function + import to load dynamically

const List =() => import('@/components/list.vue')
const router = new vueRouter({
	routes:[{
		path:'/list',
		component:List
	}]
})

2) Method 2: use the arrow function + require to load dynamically

const router = new vueRouter({
	routes:[{
		path:'/list',
		component:resolve => import(['@/components/list]',resolve)
	}]
})

3) Method 3: the on-demand loading can also be realized by using the require.ensure technology of webpack. Multiple routes specify the same chunkName and will be merged and packaged into a js file.

// r is resolve
const List = r => require.ensure([],()=>
r(require('@/components/list')),'list');
// Routing is also a normal way of writing, which is officially recommended. It is loaded by module 
const router = new Router({
  routes: [
  {
    path: '/list',
    component: List,
    name: 'list'
  }
 ]
})
)

Tags: Javascript Interview

Posted on Wed, 06 Oct 2021 14:13:09 -0400 by madsporkmurderer