class关键字

class关键字


javascript class 面向对象
class Person {
  constructor(name, age) {
    var style = "happy";
    this.name = name;
    this.age = age;
  }
  gender = "male";
  height = 170;

  showName = () => {
    console.log("name:" + this.name);
  };

  showName2 = function () {
    console.log(this);
  };

  showAge() {
    console.log("age:" + this.age);
  }
}

var niko = new Person("Niko", 25);

console.log(niko);
console.log(Object.keys(niko));
niko.showName();
niko.showAge();
const showName1 = niko.showName;
const showName2 = niko.showName2;
showName1();
showName2();
结果:
Person {gender: "male", height: 170, name: "Niko", age: 25, showName: ƒ, showName2: ƒ}
["gender", "height", "showName", "showName2", "name", "age"]
name:Niko
age:25
name:Niko
undefined
结论:
1.在constructor中var一个变量,它只存在于constructor这个构造函数中
2.在constructor中使用this定义的属性和方法会被定义到实例上
3.在class中使用=来定义一个属性和方法,效果与第二点相同,会被定义到实例上
4.在class中直接定义一个方法,会被添加到原型对象prototype上
5.在class中使用了static修饰符定义的属性和方法被认为是静态的,被添加到类本身,不会添加到实例上
6.可以看到最后输出了个undefined, 是因为class内部的函数this指向是不确定的;一般函数通过函数形式调用的话,this就是window,而class内部默认是严格模式"use strict", this就是undefined;可以使用箭头函数固定其this指向
其他须注意的:
1.使用for...in...能获取到实例对象自身的属性和原型链上的属性
2.使用Object.keys()和Object.getOwnPropertyNames()只能获取实例对象自身的属性
3.可以通过.hasOwnProperty()方法传入属性名来判断一个属性是不是实例自身的属性
© 2025 Niko Xie