繁体   English   中英

在使用工厂函数创建的对象的属性中切换真或假

[英]toggle true or false in an property of an object created using factory function

我曾经有这个构造函数和一个原型,可以在 true 或 false 之间切换 object.status。 这里:

function Book(title, author, length, status){
    this.title = title;
    this.author = author;
    this.length = length;
    this.status = status;
}

Book.prototype.toggleStatus = function (){
    this.status = !this.status;
}

现在我想在工厂函数中创建原型。 这是我去过的地方:

const Book = function (title, author, length, status) {

            const toggleStatus = () => status = !status

           return {title, author, length, status, toggleStatus}

如果我调用 someObject.toggleStatus(),我会在日志中收到反转的布尔状态,但它不会更改对象本身 kvp 上的,这是我的最终目标。 如果可能的话,我希望使用原型来制作。

让处理程序重新分配返回对象的属性:

const Book = function (title, author, length, status) {
  const book = { title, author, length, status, toggleStatus: () => book.status = !book.status };
  return book;
};

另一个更接近于在闭包内重新分配变量名称的原始代码的选项(更奇怪)是将status改为 getter:

const Book = function (title, author, length, status) {
  return {
    title,
    author,
    length,
    get status() {
      return status;
    },
    // add a setter too if needed
    toggleStatus: () => status = !status
  };
};

如果除了工厂函数之外还想使用原型,请使用Object.create从原型创建实例:

 const Book = function (title, author, length, status) { const b = Object.create(bookProto); return Object.assign(b, { title, author, length, status }); }; const bookProto = { toggleStatus() { this.status = !this.status; } }; const b = Book('title', 'author', 7, true); console.log(b.status); b.toggleStatus(); console.log(b.status); b.toggleStatus(); console.log(b.status); b.toggleStatus();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM