1-箭头函数
箭头函数的特征:
1、箭头函数没有arguments概念
2、箭头函数不能当做构造函数使用,不能使用new命令
3、剪头的函数的this指向的定义的时候所在的对象
2-call apply bind修改this指向
this指向问题:
1、普通函数中this指向 ---> window
2、事件函数中this指向 ---> 事件源
3、构造函数中this指向 ---> 实例对象
4、具体对象中this指向 ---> 当前对象
5、箭头函数的this指向 ---> 定义时所在的对象
修改函数this指向:
1、call: 函数.call(参数1,参数2,参数3)
第一个参数是所要指向的对象,其余参数为函数的实参
2、apply: 函数.apply(参数1,[参数2,参数3])
第一个参数是所要指向的对象,其余参数为函数的实参,用数组的方式呈现
3、bind: 函数.call(参数1,参数2,参数3)
不能直接被调用,返回的是一个新的函数
call和apply都可以直接调用函数,只是传递实参的方式不同
bind不可以直接调用函数,返回的是一个新的函数
var stu = {
name: 'zs'
}
function fun ( x, y) {
console. log ( this , x, y) ;
}
fun ( 1 , 2 , 3 ) ;
fun. call ( stu, 1 , 2 )
fun. apply ( stu, [ 3 , 4 ] ) ;
var fn = fun. bind ( stu, 5 , 6 ) ;
fn ( ) ;
3-es6类
类的概念:es6中类的概念,只是一个“语法糖”.es6实现的关于类的大多数功能,都可以通过 之前的语法来实现
class Product {
constructor ( title, price) {
this . title = title;
this . price = price;
this . joinCar = function ( ) {
console. log ( '加入购物车' ) ;
}
}
buy ( ) {
console. log ( '确认购买' ) ;
}
}
var pro1 = new Product ( '无人机' , 399 )
pro1. joinCar ( ) ;
pro1. buy ( ) ;
console. log ( pro1. hasOwnProperty ( 'price' ) ) ;
console. log ( pro1. hasOwnProperty ( 'buy' ) ) ;
console. log ( pro1. __proto__ == Product. prototype) ;
4-constructor
constructor方法是类的默认方法,一个类必须有constructor方法,如果没有显示
系统会默认添加了constructor方法,通过new命令生成实例对象的时候,会自动调用该方法
constructor方法默认返回的是实例对象,可以指定返回一个别的对象
class Person {
constructor ( name) {
return Array ( 1 , 2 , 3 , 4 , 5 )
this . name = name;
}
}
var stu = new Person ( '王大陆' ) ;
console. log ( stu) ;
5-es6继承
在es6中通过extends关键字实现继承
class Person {
constructor ( name, sex, age) {
this . name = name;
this . sex = sex;
this . age = age;
}
login ( ) {
console. log ( this . name+ '浏览了网页' ) ;
}
}
class Student extends Person {
constructor ( name, sex, age, id) {
super ( name, sex, age) ;
this . id = id;
}
login ( ) {
console. log ( '学生' + this . name+ '访问了网站' ) ;
}
}
var stu = new Student ( '加多宝' , 'man' , 25 , '0101' ) ;
stu. login ( ) ;
console. log ( stu) ;
继承的相关问题:
在子类中,只有调用了super方法才能使用this,否则会报错
子类的构建是基于父类的构造函数加工的,只有super方法才能使用父类实例
如果super里面不写参数,会造成传参失败的情况
6-静态方法和静态属性
静态方法和静态属性可以用过类直接调用,不需要实例对象
在类的方法前面加上static表示该方法为静态方法,,只有类可以调用
静态属性指的是类的属性,通过类名.静态属性值直接赋值,只有类可以调用
静态方法和静态属性都是可以继承的,不是复制的,实例对象的属性是复制过来的
class Fun {
static buy ( ) {
console. log ( '我将收购腾讯' ) ;
}
buy ( ) {
console. log ( '腾讯将被我收购' )
}
}
Fun. names = 'shop' ;
var fn = new Fun ( ) ;
fn. buy ( ) ;
Fun. buy ( ) ;
console. log ( Fun. names) ;
class Fn extends Fun {
constructor ( ) {
super ( ) ;
}
}
Fn. buy ( ) ;
console. log ( Fn. names) ;
console. log ( Fn. hasOwnProperty ( 'buy' ) ) ;
console. log ( Fun. hasOwnProperty ( 'buy' ) ) ;
7-私有方法
私有方法是常见需求,但是es6不提供
私有方法只能在类中调用 如果方法以_开始,只能在类中调用,但是目前实现不了