当前位置:网站首页>JS__ This, arguments, cloning, ternary operator__ Duyi
JS__ This, arguments, cloning, ternary operator__ Duyi
2022-06-25 20:58:00 【Leap soil and tea】
this
- Function precompile process this --> window
function test(c) {
//var this = Object.create(test.prototype);
//{
//__proto__ : test.prototype
//}
var a = 123;
function b() {
}
}
AO {
arguments : [1],
this : window,//GO overall situation
c : 1,
a : undefined,
b : function () {
}
}
test(1);
new test();// Implicit this Pointing prototype
function test() {
console.log(this);
}
test();//window{} --> overall situation
- In the global scope this --> window
this //window{}
- call/apply You can change the function runtime this Point to
- obj.func(); func() Inside this Point to obj
var obj = {
a : function () {
// Method
console.log(this.name)
},
name : 'abc'
}
obj.a();// Who is calling a Method , Methods this Who is the this-->obj
test questions :
1.var name = "222";
var a = {
name : "111",
say : function () {
console.log(this.name);
}
}
var fun = a.say;// Function reference
fun()//222 Functions execute globally this-->window
a.say()// Called 111
var b = {
name : "333",
say : function (fun) {
//this --- > b
fun();// Not being called is global Go through the precompile process function () {console.log(this.name);} this --> window
}
}
b.say(a.say);//222
b.say = a.say;//a.say Copy the function of to b.say Replace with
b.say();// Called 333
summary : If no one calls it, it means the whole situation
2.var foo = '123';
function print(){
var foo = '456';
this.foo = "789";
console.log(foo);
}
print();//this-->window 456
Variant 1:
var foo = 123;
function print() {
this.foo = 234;//this-->window
console.log(foo);// The print is global foo, Overall foo Was changed to 234
}
print();//234
Variant 2:
var foo = 123;
function print() {
//var this = Object.create(print.prototype) this Don't point to window
this.foo = 234;
console.log(foo);// The print is global foo, Overall foo Not changed
}
new print();//123
3. function test() and new test() What are the results of ?
var a = 5;
function test() {
a = 0;
alert(a);//0
alert(this.a);//5
var a;
alert(a);//0
}
test();
AO {
a : 0,
this : window
}
function test() {
var this = {
__proto__ : test.prototype;
}// There's no a
a = 0;
alert(a);//0
alert(this.a);//undefined
var a;
alert(a);//0
}
new test();
AO {
a : 0,
this : {
}
}
Written examination questions
1. precompile : Function declaration overall promotion
var x = 1, y = z = 0;
function add(n) {
return n = n + 1;
}
y = add(x);//4
function add(n) {
return n = n + 3;
}
z = add(x);//4
2. Which of the following are javascript Language typeof Possible results : AC
//boolean,number,string,undefined,object,function
A.string
B.array
C.object
D.null
3. Look below alert What is the result
function b(x, y, a) {
arguments[2] = 10;//a
alert(a);//10
}
b(1, 2, 3);// Every bit of the argument list and every bit of the formal parameter list are mapped to each other
If the function body is changed to the following , What's the result ?
a = 10;
alert(arguments[2]);//10
4. Comma operator , Only return to the back one
var f = {
function f() {
return "1";
},
function g() {
return 2;
}
)();
typeof f;//number
5.
var x = 1;
if(function f() {
}) {
//true Function to expression , In parentheses f External not found
x += typeof f;//"undefined"
}
console.log(x);//"1undefined"
6. Which of the following expressions results in true: AD
A.undefined == null//true NaN Not equal to any number, including itself
B.undefined === null//false Not absolutely equal to ,NaN Nor is it absolutely equal to itself
C.isNaN("100")//false experience Number Implicit type conversion
D.parseInt("1a") == 1;//true
{
} == {
} //false An object represents a room , Reference value comparison address , Equal addresses make equal
var obj1 = obj;// Point to the same room
obj1 == obj//true
7. Please read the following code , Write the execution result of the following program :
function print() {
console.log(foo);
var foo = 2;
console.log(foo);
console.log(hello);
}
print(); Execution results :Error:hello is undefined
8. Please read the following code , Write the execution result of the following program :
function print() {
var test;// By function Cover
test();
function test() {
console.log(1);
}
}
print();//1
9. Please read the following code , Write the execution result of the following program :
function print() {
var x = 1;
if(x == "1") console.log("One!");// An implicit type conversion occurs
if(x === "1")console.log("Two!");// No implicit type conversion occurs
}
print();//One
10. Please read the following code , Write the execution result of the following program :
function print() {
var marty = {
name : "marty",
printName : function() {
console.log(this.name);
}
}
var test1 = {
name :"test1"
};
var test2 = {
name :"test2"
};
var test3 = {
name :"test3"
};
test3.printName = marty.printName;
var printName2 = marty.printName.bind({
name:123});
marty.printName.call(test1);//test1
marty.printName.apply(test2);//test2
marty.printName();//marty
printName2();//
test3.printName();//test3
}
print();
11. Please read the following code , Write the execution result of the following program :
var bar = {
a : "002"};//{a : 'a'}
function print() {
bar.a = 'a';
Object.prototype.b = 'b';
return function inner() {
console.log(bar.a);//a
console.log(bar.b);//b
}
}
print()();// first () Return function inner the second () Execute function inner
arguments
- arguments.callee Refer to the function itself
function test() {
console.log(arguments.callee == test);//true
}
test();
The immediate execution function does not have a name , If you want to call recursively , What does a function reference say ?arguments.callee Can solve the problem
var num = (function(n){
if(n == 1){
return 1;
}
return n * arguments.callee(n-1);
}(20));
function test() {
console.log(arguments.callee);//test
function demo() {
console.log(arguments.callee);//demo
}
demo();
}
test();
- func.caller-- func The called environment is ? caller No arguments Properties on , It's the function's own properties
ES5 An error will be reported in the standard mode
function test() {
demo();
}
function demo() {
demo.caller;//test
}
clone
- Shallow cloning : Clones obj1 The attribute change of will be linked obj Change at the same time .
var obj = {
name : 'abc',
age : 123,
sex : 'female',
card : ['visa','unionpay']
}
var obj1 = {
}
function clone(origin, target) {
var target = target || {
};// Compatibility
for(var prop in origin) {
target[prop] = origin[prop];
}
return target;
}
clone(obj, obj1);
obj1.card.push('master');
//obj1.card—->['visa','unionpay','master']
//obj.card—>['visa','unionpay','master']
2. Deep cloning : Clone the same attributes , But the room is different , Changing one will not change the other .
Analysis link : Reference values only consider arrays and objects . Circular judgement , When encountering arrays and objects, you should judge .
var obj = {
name : "abc",// Original value
age : 123,// Original value
card : ['visa', 'master'],// Reference value
wife : {
name : "bcd",
son : {
name : "aaa"
}
}
}
var obj1 = {
name : "abc",//obj.name
age : 123,
card : [obj.card[0],obj.card[1]],
wife : {
name : "bcd",
son : {
name : "aaa"
}
}
}
// Traversing objects for(var prop in obj) Arrays can also for in, Arrays are special objects prop Subscript subscript
// 1. Judge whether it is the original value typeof()—->object
// 2. Determine whether it's an array or an object ( Reference value ) toString instanceof and constructor There is a problem in the parent-child domain
// 3. Create the corresponding array or object
// 4. recursive
First judge obj The value type of the property , Filter out object type (null Also need to consider ), Use toString Method to distinguish an array from an object , Call the original function recursively .
var obj = {
name : 'abc',
age : 123,
gender : 'male',
card : {
card1 : 'visa',
card2 : 'master'
}
};
var obj1 = {
};
function deepClone(origin, target){
var target = target || {
},// Fault tolerance , In case the user doesn't transmit target Parameters
toStr = Object.prototype.toString,
arrStr = "[object Array]";
for(var prop in origin){
if(origin.hasOwnProperty(prop)){
// Judge whether it is your own attribute , Avoid taking attributes on the prototype chain
if(origin[prop] !== 'null' && typeof(origin[prop]) == 'object'){
// Judge Absolutely not equal to null,typeof yes object--> Reference value
// if(toStr.call(origin[prop]) == arrStr){// Determine whether it is an object or an array
// target[prop] = [];// Create corresponding arrays and objects
// }else{
// target[prop] = {};
// }
target[prop] = (toStr.call(origin[prop]) == arrStr) ? [] : {
};
deepClone(origin[prop], target[prop]);
}else{
// Judge Original value exit
target[prop] = origin[prop];
}
}
}
return target;
}
deepClone(obj, obj1);
//obj.card.push('abc')
//obj1.card-->["visa","master"]
Ternary operator
conditional ? yes : no And it will return the value
var num = 1 > 0 ? 2 + 2 : 1 + 1;//4
var num = 1 > 0 ? ("10" > "9" ? 1 : 0) : 2; //0 Inside () Bitwise ratio ASCI code
边栏推荐
- Splunk series: Splunk data import (II)
- [deep learning series] - visual interpretation of neural network
- How to close gracefully after using jedis
- How to buy the millions of medical insurance for children? How much is it a year? Which product is the best?
- Nmap is simple and practical
- HMS core actively explores the function based on hardware ear return, helping to reduce the overall singing delay rate of the singing bar by 60%
- Cloud development practice of the small program for brushing questions in the postgraduate entrance examination - page design and production (home page of the question bank, ranking page, my)
- Docker failed to remotely access 3306 after installing MySQL
- Is flush app regular? Is it safe or not
- What are the differences between domestic advanced anti DDoS servers and overseas advanced anti DDoS servers?
猜你喜欢
Understand the offline mixing technology in the industry
Chrome plugin installation

Several methods of obtaining function annotation text on pycharm

Slenium tips: how to handle some dialog boxes that may appear on Web pages

Bank digital transformation layout in the beginning of the year, 6 challenges faced by financial level structure and Countermeasures
R language momentum and Markowitz portfolio model implementation
Yunzhisheng atlas supercomputing platform: computing acceleration practice based on fluid + alluxio (Part I)
How to play one to many in JPA?

After 20 days' interview, I finally joined Ali (share the interview process)
8 minutes to understand the wal mechanism of tdengine
随机推荐
Leetcode daily [2022 - 02 - 18]
How does jest expose specific problems in complex judgment conditions?
Share several Threat Intelligence platforms
启牛学堂证券开户安全嘛?
How can the intelligent transformation path of manufacturing enterprises be broken due to talent shortage and high cost?
Soft test intermediate simple notes
Live broadcast preview | front line experts invite you to talk: the value of data science enabling multiple application scenarios
Paddledtx v1.0 has been released, and its security and flexibility have been comprehensively improved!
HMS core actively explores the function based on hardware ear return, helping to reduce the overall singing delay rate of the singing bar by 60%
Molecular dynamics - basic characteristics of molecular force field
Local variables and global variables in C language
Redis core principle and design idea
1.0-mq getting started and using
Xshell mouse configuration
Understand the offline mixing technology in the industry
How does zhiting home cloud and home assistant access homekit respectively? What is the difference between them?
Node installation method you don't know
Log4j2 vulnerability detection tool list
MySQL installation tutorial
An unusual interview question: why doesn't the database connection pool adopt IO multiplexing?