Adding custom properties to a function

后端 未结 10 772
独厮守ぢ
独厮守ぢ 2020-11-27 10:34

Searching for appropriate answer proved difficult because of the existence of many other problems related to my keywords, so I\'ll ask this here.

As we know, functio

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 11:24

    test = (function() {
      var a = function() {
        console.log("test is ok");
      };
      a.prop = "property is ok";
      a.method = function(x, y) {
        return x + y;
      }
      return a
    })()
    
    test();
    console.log(test.prop);
    console.log(test.method(3, 4));

    Alternatively you have to use getters and setters

    var person = {
      firstName: 'Jimmy',
      lastName: 'Smith',
      get fullName() {
        return this.firstName + ' ' + this.lastName;
      },
      set fullName(name) {
        var words = name.toString().split(' ');
        this.firstName = words[0] || '';
        this.lastName = words[1] || '';
      }
    }
    console.log(person.firstName);
    console.log(person.lastName);
    console.log(person.fullName);
    person.fullName = "Tom Jones";
    console.log(person.fullName);

提交回复
热议问题