[英]Uncaught TypeError: Person is not a constructor
var Person = (function () { var name = Symbol('name'); class Person { constructor(name) { this[name] = name } getname() { return this[name]; } } }()); var person = new Person(); console.log(person.getname())
I'm making a small example via a tutorial on Google. 我正在通过Google教程制作一个小例子。 This example prevents to access property this.name from outside scope. 本示例防止从外部范围访问属性this.name。 But I'm getting error 但是我出错了
Uncaught TypeError: Person is not a constructor. 未捕获的TypeError:Person不是构造函数。
How can I solve it? 我该如何解决?
function Person (name) { this.name = name; this.getname=function() { return this[name]; }; } var person = new Person('name'); console.log(person.getname())
You have to return Person class and use another variable name for storing symbol since it's the same as constructor argument name: 您必须返回Person类并使用另一个变量名称来存储符号,因为它与构造函数参数名称相同:
var Person = (function () { var nameSymbol = Symbol('name'); return class Person { constructor(name) { this[nameSymbol] = name; } getname() { return this[nameSymbol]; } } }()); var person = new Person('John'); console.log(person.getname())
You don't have to enclose class within a function. 您不必将类包含在函数中。 ES5 needs functions to create a class. ES5需要使用函数来创建类。 The code snippet you have provides makes a mix of ES5 and ES6. 您提供的代码片段混合了ES5和ES6。 Simple use as below: 简单使用如下:
class Person {
constructor(name) {
this.name = name
}
getname() {
//return this.name;
return this['name'];
}
}
let person = new Person('Alex');
console.log(person.getname());
If you are using [] notation to access object properties then remember that it must be a string iewrapped in quotes 如果使用[]表示法访问对象属性,请记住它必须是一个字符串,即用引号引起来
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.