setters and getters in javascript

setters and getters in javascript

本文关键字:javascript in getters and setters      更新时间:2023-09-26

我正在尝试学习JavaScript中的类,setters和getters..但是我的代码不起作用..它提醒未定义..这是我的代码

function Person () {
	name:"something"
	
Person.prototype = {
		get Name (){
			return name;
			},
			set Name (val){
				this.name = val;
				
			}
};
};
var person = new Person(); 
alert(person.name);

这是在您的示例中设置 getter 和 setter 的正确方法:

    function Person () {
        this.name = "something";
    }
    Person.prototype = {
        get Name() {
            return this.name;
        },
        set Name(val) {
            this.name = val;
        }
    };
    var person = new Person();
    person.Name = 'example';
    alert(person.name);

JS 是基于原型的,那么你可以定义属性:

function Person(){
   this._name = '';
}
Object.defineProperty(Person.prototype, "name", {
            get: function(){
                return this._name;
            },
            set: function(value){
                this._name= value;
            },
            enumerable:true,
            configurable: true
});

然后你可以设置或获取属性"名称"

var p = new Person()
p.name = 'Stackoverflow'
alert(p.name) // Stackoverflow

在 ES6 中可以使用关键字 class ,例如:

class Person {
   constructor() {
     this.name = '';
  }
}