Function(console.log('Hello,Jim!'));
new Function(console.log('Hello,Jim!'));
当我们需要实现某个功能(如登录)的时候,我们可能会定义一下函数
function login(usrname,password){
}
上面的写法等价于全局定义了一个function类型的login变量
var login = function(usrname,password){
}
ES6之后,引进了箭头函数,我们可以写成一下形式(注意:普通函数跟箭头函数有一些的区别)
var login = (usrname,password)=>{
}
login('Jim','123456');// 直接调用
new login();// 借助new关键字
var TestThis = function(){
if(this instanceof Window){
console.log('Window')
}
if(this instanceof TestThis){
console.log('TestThis')
}
};
TestThis();// Window
new TestThis();// ThisTest
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 constructor
var myFunc = ()=>{console.log(this};
Function(myFunc()) // Window
// 父类定义
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
var tmpPrototype = Object.create(prototype)
等价下面写法
var create = function(prototype){
function func(){}
func.prototype = prototype;
return new func
}
var tmpPrototype = create(prototype)
var counter = function(){
counts = 0; //函数级别 静态变量
return function(){ // 返回闭包
counts++;
console.log(counts)
}
}
var myCounter = counter();
myCounter() // 1
myCounter() // 2
myCounter() // 3