如何在Vanila JS中实现可观察的行为

时间:2018-12-19 00:44:19

标签: javascript oop observable prototype

我正在尝试在Vanila js中实现敲除观察计算行为

在react中,这两个变量都将处于状态并计算全名

我们如何在vanila js中实现相同目标

function person(firstname,lastname) {
    this.firstname = firstname;
    this.lastname = lastname;
    this.fullName = `${this.firstname}${this.lastname}`
}

var person1 =new person("abc","k");
Object.defineProperty(person,'firstname',{

  get: () => {
      return person1['firstname'];
  },
  set: (name) => {
      person1['firstname'] = name;
  }
  
});
Object.defineProperty(person,'lastname',{

  get: () => {
      return person1['lastname'];
  },
  set: (name) => {
      person1['lastname'] = name;
  }
});

Object.defineProperty(person,'fullName',{
  
  get: () => { 
    return `${person1['firstname']}-${person1['lastname']}`;
  }
  
});
console.log(person1.firstname, "firstnmae");
person1.firstname ="sah";
console.log(person1.lastname, "lastname");
console.log(person1.fullName, "fullname");

1 个答案:

答案 0 :(得分:2)

看下面的代码:

var person = {

    firstname: 'abc',
    lastname: 'k'

};

Object.defineProperty(person,'fullName',{
  
    get: function() {
    
        return `${this['firstname']}-${this['lastname']}`;
    
    }

});

var person1 = Object.create( person );

console.log(person1.firstname, "firstnmae");
person1.firstname ="sah";
console.log(person1.lastname, "lastname");
console.log(person1.fullName, "fullname");

  1. 无需通过firstname定义lastname.defineProperty,因为默认情况下,这些 setter getter 将起作用当你写它们的时候。

  2. 您应该使用此语法,因为这样以后更容易阅读/维护,否则,如果您希望坚持使用 constructor 语法,请执行以下操作:

    < / li>

var person = function() {};

Object.defineProperty(person,'firstname',{

    value: 'abc',
    writable: true

});

Object.defineProperty(person,'lastname',{

    value: 'k',
    writable: true

});

Object.defineProperty(person,'fullName',{
  
    get: function() {
    
        return `${this['firstname']}-${this['lastname']}`;
    
    }

});

var person1 = Object.create( person );

console.log(person1.firstname, "firstnmae");
person1.firstname ="sah";
console.log(person1.lastname, "lastname");
console.log(person1.fullName, "fullname");

  1. 我认为您需要对Object.create() and MDN is the best place进行更多调查。

  2. arrow-functions具有词法 this,请注意!

  3. 此语法可能为您澄清了有关Object.create()的一些观点:

var person = function() {};

person.prototype.firstname = 'abc';
person.prototype.lastname = 'k';

Object.defineProperty(person.prototype,'fullName',{
  
    get: function() {
    
        return `${this['firstname']}-${this['lastname']}`;
    
    }

});

var person1 = Object.create( person.prototype );

console.log(person1.firstname, "firstnmae");
person1.firstname ="sah";
console.log(person1.lastname, "lastname");
console.log(person1.fullName, "fullname");