js进阶小知识

关于函数名和var声明的变量名相同的情况
function a() {
    console.log(10);
}
var a;
console.log(a); // 打印 a() 函数的函数体
a();           // 10
a = 3;
  • 1、函数和var声明的变量作用域会发生提升
  • 2、han’shu提升会优先与变量提升
  • 3、如果函数和变量名一样,并且变量没有被赋值,则函数生效
this相关
  • 1、被调用的函数,点前面是谁this就是谁,否则为window
this.a = 20;
var test = {
    a: 40,
    init() {
        console.log(this);
        console.log(this.a);
    }
}
test.init();    // 输出test的函数体和  40
var fn = test.init;
fn();           // 输出window和 20
  • 2、在闭包的情况下,没有函数去调用go(),所以this的上下文就是this
this.a = 20;
var test = {
    a: 40,
    init() {
        function go() {
            console.log(this);
            console.log(this.a);
        }
        go();
    }
}
test.init();  // 输出window和 20
  • 3、箭头函数中的this只取决于包裹箭头函数的的第一个普通函数的this
this.a = 20;
var test = {
    a: 40,
    init: () => {
        console.log(this);
        console.log(this.a);
    }
}
test.init();   // 输出window和 20
function可以new,es6中的简写方式不可以new
var s = {
    a: function() {
        console.log(1)
    },
    b() {
        console.log(2)
    }  
}
var f = s.a.bind(this)
new f()         // 1
var p = s.b.bind(this)
new p()       // p is not a constructor
当使用new创建函数时,this指向当前函数的实例
var s = {
    a: function() {
        console.log(this)
    } 
}
var f = s.a.bind(this)
new f()    // 输出实例a()
如何将一个字符串变为一个数组
// 方法一
Array.from("abc"); // ["a", "b", "c"]

// 方法二
[...new Set("abc")]; // ["a", "b", "c"]

// 方法三
"abc".split("");    // ["a","b","c"]
只有new一个函数的时候,在函数上找不到才会去原型链上找
function test() {}
test.prototype.a = 1;
test.a          // undefined
function test() {}
test.prototype.a = 1;
var test_ = new test();
test_.a;        // 1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值