// 创建方式不同
// 函数
function Fn1() {}
// 类
class Person {}
// class类声明变量不会提升;函数可以提升
Fn2()
function Fn2() {
console.log('1');
}
new Person2().show() // error: Cannot access 'Person2' before initialization 这个错误意味着代码试图在一个类初始化完成之前就访问它
class Person2 {
show() {
console.log('2');
}
}
// class类必须使用new关键字调用;函数不需要
Fn2()
function Fn3() {
console.log('1');
}
class Person3 {
show() {
console.log('2');
}
}
Person3.show() // Person3.show is not a function
// class类里面的方法不可以被枚举;函数可以
// 类
class Person4 {
constructor(name) {
this.name = name;
}
show() {
console.log(`这是一台${this.name}电脑`)
}
static staticShow() {
console.log("这是静态方法")
}
}
const a = new Person4('联想');
for(let prop in a) {
console.log('prop', prop);
}
// 函数
function Fn4(name) {
this.name = name
}
Fn4.prototype.show = function () {
console.log(`我的名字叫:${this.name}`);
}
Fn4.staticShow = function() {
console.log("这是静态方法")
}
let fn = new Fn4('联想')
for(let prop in fn) {
console.log('prop', prop);
}
// 函数定义可以当构造函数又可以当普通函数;class类是创建对象的模板,不能当做普通函数, 类的方法不能作为构造函数
// 函数
function Fn5(name) {
this.name = name
}
Fn5.prototype.show = function (age) {
console.log(`我的年龄是:${age}`);
}
let fn5 = new Fn5('Join')
let Show = fn5.show
new Show(12)
// 类
class Person5 {
constructor(name) {
this.name = name;
}
show(age) {
console.log(`我的年龄是:${age}`);
}
static staticShow() {
console.log("这是静态方法")
}
}
let p5 = new Person5('Join')
let Show2 = p5.show
new Show2(12) // error:Show2 is not a constructor
// todo class类默认使用了严格模式,函数除非声明关键字'use strict'
js里面函数与类的区别
于 2024-04-27 10:04:39 首次发布