gpt4 book ai didi

javascript - 如何删除属性(property)编号?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:49:39 25 4
gpt4 key购买 nike

function Student(name, sclass, year, number, submissionYear)
{
this.name = name;
this.sclass = sclass;
this.year = year;
this.number = number;
this.submissionYear = submissionYear;
}

// Edit : added OP's code from comments
let Manuel = new Student("Manuel", "lesi", "3", "98789", 2014);
console.log(Manuel.number);
delete Student.number;
console.log(Student); // The object still includes number as property

如何删除属性编号,因为删除 Student.number 不起作用。

最佳答案

...as the delete Student.number is not working

Student 没有 number 属性,所以没有什么可以删除的。使用 new Student 创建的对象可以。例如:

function Student(name, sclass, year, number, submissionYear)
{
this.name = name;
this.sclass = sclass;
this.year = year;
this.number = number;
this.submissionYear = submissionYear;
}

var s = new Student();
console.log("number" in s); // true
delete s.number;
console.log("number" in s); // false

如果你想创建一个 Student 版本来创建没有 number 属性的对象,那是可能的,但这是个坏主意:

function Student(name, sclass, year, number, submissionYear)
{
this.name = name;
this.sclass = sclass;
this.year = year;
this.number = number;
this.submissionYear = submissionYear;
}

function NumberlessStudent() {
Student.apply(this, arguments);
delete this.number;
}
NumberlessStudent.prototype = Object.create(Student.prototype);
NumberlessStudent.prototype.constructor = NumberlessStudent;

var n = new NumberlessStudent();
console.log("number" in n); // false

或者最好在 ES2015+ 中使用 class 语法:

class Student {
constructor(name, sclass, year, number, submissionYear) {
this.name = name;
this.sclass = sclass;
this.year = year;
this.number = number;
this.submissionYear = submissionYear;
}
}

class NumberlessStudent extends Student {
constructor(...args) {
super(...args);
delete this.number;
}
}

const n = new NumberlessStudent();
console.log("number" in n); // false

这是个坏主意,因为以这种方式设置继承,子类实例 (NumberlessStudent) 应该具有父类(super class) (Student) 实例的特性。

关于javascript - 如何删除属性(property)编号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55026322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com