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 propertyRun Code Online (Sandbox Code Playgroud)
我如何删除属性号,因为删除Student.number无效。
...因为删除Student.number不起作用
Student没有number属性,因此没有要删除的内容。用new Studentdo 创建的对象。因此,例如:
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); // falseRun Code Online (Sandbox Code Playgroud)
如果要创建一个版本,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); // falseRun Code Online (Sandbox Code Playgroud)
或者最好在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); // falseRun Code Online (Sandbox Code Playgroud)
这是一个坏主意,因为以这种方式设置继承时,子类实例(NumberlessStudent)应该具有超类(Student)实例的功能。
您Student是一个构造函数,因此Student.number除非它是静态方法,否则是不正确的(但这不是您的情况)。
您必须创建一个对象Student,即
const student = new Student('Mell', 'A', 1990, 500, 1994);
Run Code Online (Sandbox Code Playgroud)
那你可以用
delete student.number
Run Code Online (Sandbox Code Playgroud)
请以以下代码段为例:
const student = new Student('Mell', 'A', 1990, 500, 1994);
Run Code Online (Sandbox Code Playgroud)
您可以在此处找到有关JavaScript中的构造函数和对象的更多信息。