应网友的要求写的一个 对象属性访问器的判断

it2026-04-16  3

function Person(name) { this.name = name; this.flag = 0; Object.defineProperty(this, 'name', { get: function() { return name;}, set: function(newName) { if (this.flag) { name = newName; this.flag = 0; } return name; } }); this.setName = function(newName) { this.flag = 1; this.name = newName; } }; var manx = new Person('manx'); console.log(manx.name); // manx manx.name = "bob"; console.log(manx.name); // manx manx.setName('jack'); console.log(manx.name); // 'jack'

  

转载于:https://www.cnblogs.com/ax-null/p/7112809.html

最新回复(0)