文章目录
- 1. function与类Function的区别
- 2. 函数的等价写法
- 3. 函数的使用场景
- 4. 两个不同使用场景下的this关键字
- 5. 面向对象中的继承实现:prototype关键字
- 6. 理解闭包
1. function与类Function的区别
- Function 用于直接执行定义的javascript代码
Function(console.log('Hello,Jim!'));
new Function(console.log('Hello,Jim!'));
- function用于定义函数或者(详见下面描述)
2. 函数的等价写法
当我们需要实现某个功能(如登录)的时候,我们可能会定义一下函数
function login(usrname,password){
}
上面的写法等价于全局定义了一个function类型的login变量
var login = function(usrname,password){
}
ES6之后,引进了箭头函数,我们可以写成一下形式(注意:普通函数跟箭头函数有一些的区别)
var login = (usrname,password)=>{
}
3. 函数的使用场景
- 作为实现某个功能的函数
login('Jim','123456');// 直接调用
- 定义面向对象中的类
new login();// 借助new关键字
4. 两个不同使用场景下的this关键字
- function内第一个局部变量是this,this在不同的使用场景下,指向的对象不一样
var TestThis = function(){if(this instanceof Window){console.log('Window')}if(this instanceof TestThis){console.log('TestThis')}
};
TestThis();// Window
new TestThis();// ThisTest
- 箭头函数不可以使用new,函数中的this指向Window(除非箭头函数被Function包裹直接执行)
var TestThisByArrowFunc = ()=>{if(this instanceof Window){console.log('Window')}if(this instanceof TestThisByArrowFunc){console.log('TestThisByArrowFunc')}
}
// 没有 ojbect类型的 prototype无法使用instanceof
TestThisByArrowFunc();// Window + Uncaught TypeError: Function has non-object prototype 'undefined' in instanceof check
//没有构造器无法使用new
new TestThisByArrowFunc();// VM742:1 Uncaught TypeError: TestThisByArrowFunc is not a constructorvar myFunc = ()=>{console.log(this};
Function(myFunc()) // Window
5. 面向对象中的继承实现:prototype关键字
- function 定义基本类跟类实例变量
- prototype 定义共享方法以提高性能,通过原型链实现方法继承
- apply/call 将子类的this指针传给父类,让父类的实例变量赋值给子类
// 父类定义
var Person = function(name,age){this.name = name;this.age = age;
}
Person.prototype.toString = function(){console.log(this);
}
// 子类定义
var Teacher = function(name,age,subject){Person.call(this,name,age) // 将子类this指针替换掉父类this,让父类为子类添加字段值this.subject = subject;
}
Teacher.prototype = Object.create(Person.prototype); // 创建中间原型实例
Teacher.prototype.constructor = Teacher; // 修改原型实例构造函数为子类// 测试
var teacher = new Teacher('Jim',35,'Math');
console.log(teacher.name) // Jim
console.log(teacher.age) // 35
console.log(teacher.subject) // Math
teacher.toString() // Teacher {name: 'Jim', age: 35, subject: 'Math'}
console.log(teacher instanceof Person) // true
console.log(teacher instanceof Teacher) // true
- 上面例子,通过Object.create创建中间原型实例
var tmpPrototype = Object.create(prototype)
等价下面写法
var create = function(prototype){function func(){}func.prototype = prototype;return new func
}
var tmpPrototype = create(prototype)
6. 理解闭包
- 定义:能够访问到函数级别变量的函数成为闭包,函数级别的变量相对于闭包而已是静态变量
- 通过实现一个计数器来理解闭包
var counter = function(){counts = 0; //函数级别 静态变量 return function(){ // 返回闭包counts++;console.log(counts)}
}
var myCounter = counter();
myCounter() // 1
myCounter() // 2
myCounter() // 3