const username1 = ‘LiHao‘; //一般字符串
const username2 = `LiHao`; //模板字符串
console.log(username1,username2,username1 === username2) //LiHao LiHao true
//一般字符串拼接
const person = {
username :‘LiHao‘,
age:18,
sex:‘male‘
};
const info = ‘我的名字是‘ + person.username + ‘,性别:‘ + person.sex + ‘,年龄:‘ + person.age;
console.log(info); //我的名字是LiHao,性别:male,年龄:18
//模板字符串
const info = `我的名字是${person.username},性别:${person.sex},年龄:${person.age}`;
console.log(info); //我的名字是LiHao,性别:male,年龄:18
当和其他东西一起使用的时候,使用模板字符串,方便注入
其他情况下使用模板字符串或一般字符串都可以
一般字符串
const info =‘第一行 第二行‘;
console.log(info); // 第一行 第二行
const info =‘第一行\n第二行‘; //转义字符 \n 换行
console.log(info); // 第一行
// 第二行
模板字符串
//第一种写法
const info =`第一行\n第二行`; //转义字符 \n 换行
console.log(info); // 第一行
// 第二行
//第二种写法
const info =‘第一行
第二行‘; // 直接换行
console.log(info); // 第一行
// 第二行
模板字符串中,所有的空格、换行或者缩进都会被保留在输出之中(你怎么写就怎么原样输出)
const info = `\``; // \转义字符
console.log(info); // `
const info = `\`\\`;
console.log(info); // `
const username = ‘LiHao‘;
const person = {age:18,sex:‘male‘};
const getSex = function(sex){
return sex === ‘male‘?‘男‘:‘女‘;
}
const info = `${username},${person.age + 2 },${getSex(person.sex)}`;
console.log(info); //LiHao, 20, 男
// 可以调用函数 也可以运算 只要最终可以得出一个值的就可以通过${}注入到字符串模板中
//箭头函数写法
const add = (x,y) => {
return x + y;
};
console.log(add(1,1)); // 2
const/let 函数名 参数 => 函数体
//声明形式
function add() {}
//声明形式->函数表达式形式
const add = function () {};
const add = () => {
}
//单个参数可以省略圆括号const add = x => { return x + 1;};console.log(add(1)); //2//无参数参数和多个参所不可以省略圆括号const add = () => { return 1 + 1;};console.log(add()); //2
//单行函数体可以同时省略{} 和 returnconst add = (x,y) => x + y;console.log(add(1,1)); //2
多行函数体不能再简化了
const add = (x,y) => { return { value: x + y }; };console.log(add(1,1));// {value:2}// 简写 const add = (x,y) =>({ value: x + y}); console.log(add(1,1));// {value:2}
console.log(this); // window
‘use strict‘ //严格模式function add(){console.log(this);}//严格模式下指向undefinedadd();//undefined ->window(非严格模式)//只有在调用函数的时候this指向才能确定,不调用的时候,不知道指向谁//this指向和函数在哪儿调用没有的关系,只和谁调用有关const calc = { add:add};calc.add();// 指向 calcconst adder = calc.add;adder();//undefined ->window(非严格模式)
//构造函数function Person(username){ this.username = username;}const p = new Person(‘LiHao‘); //指向的是实例化过后的 p(实例对象)
const cal = { add:() => { console.log(this);}};calc.add(); //window
document.onclick = function(){ console.log(this) //document}document.addEventListener(‘click‘()=>{ console.log(this);//window},false);
function add(){console.log(arguments);}add(1,2); //Arguments(2) [1, 2, callee: ?, Symbol(Symbol.iterator): ?]
原文:https://www.cnblogs.com/LiHaoGo/p/14784837.html