- class类的创建:
class为es6的新特性,用于实现面向对象的编程
实例方法【即写在constructor内的】
一个是原型方法【定义在constructor外】
在使用new关键字实例化的时候,new的内部实现中,会改变this指向
const A = new myClass()
const B = new myClass()
A.info === B.info
A.addFunction === B.addFuntion
class myClass{
static info = 'myClass的静态属性'
static addInfo(){
console.log('myClass的静态方法')
}
constructor(name,age){
this.name = name
this.age = age
}
addFunction(){
console.log('hello world')
}
$on(){
console.log('命名可以用$开头')
}
}
var myTest = new myClass('测试',18)
- 关于function
function myFunction(name,age){
this.name = name
this.age = age
}
myFunction.prototype.addFunc = function(){
console.log('function的实例方法')
}
var myTest = new myFunction()
myTest.addFunc()
myFunction.info = 'function的静态属性'
myFunction.addFuncStatic = function(){
console.log('function的静态方法')
}
- 类和函数的区别
/*
1.变量提升问题
类不会进行变量提升,必须先声明再使用
2.new 问题
类只能用new来使用,而函数可以单独使用
3.class原型上的对象不能遍历
// 传统构造函数
function test(name,age){
this.name = name;
this.age = age;
}
test.prototype.addFun = function(){
console.log(
}
let person = new test()
for(let i in person){
console.log(i,
}
// 输出: name age addFun addFun为原型上的方法
*/