2017-02-15 38 views
0

我只想通過集名稱功能塊屬性的分配,因爲我想之前做一些格式化或驗證,看看這個例子:塞特斯在Javascript

class Animal { 
    construct(name){ 
    this.name = name; 
    return this; 
    } 

    setName(name){ 
    this.name = name; 
    } 

    getName(){ 
    return this.name; 
    } 
} 


class Dog extends Animal { 

    constructor(name){ 
    super(name); 
    return this; 
    } 

    setName(name){ 
    this.name = name.charAt(0).toUpperCase() + name.slice(1); 
    } 
} 

const dog = new Dog(); 

dog.setName('joe'); 
console.log(dog.getName()); //Joe 

dog.name = 'Bill'; // I wish this type of assignment would not work 
console.log(dog.getName()); //Bill 

這是可能做到這一點或某事類似?

回答

2

你不能鎖定了100%,但二傳手語法:

class Foo { 
 
    constructor(x) { 
 
    this.x = x; 
 
    } 
 

 
    set x(newX) { 
 
    this._x = newX.charAt(0).toUpperCase() + newX.slice(1); 
 
    } 
 

 
    get x() { 
 
    return this._x; 
 
    } 
 
} 
 

 
const foo = new Foo('hello'); 
 
console.log(foo.x); // Hello 
 
foo.x = 'goodbye'; 
 
console.log(foo.x); // Goodbye

說句公道話,雖然,我對吸氣這個邏輯,而不是二傳手。你通常在輸出上做這些美化的事情,而不是輸入。

請注意,此仍然不會阻止您的消費者編輯foo._x,JavaScript中沒有私有變量。

1

有可能真的!

如果你看一下mdn page for set,你會得到一些很好的線索,如何解決你的問題。

的一般要點是,你可以定義set propName哪個新的值設置的函數,該函數中,你可以將任何改造!

1

您可以定義訪問器,但你不能與價值觀讓他們在一起。 Mozilla documentation

不可能同時有一個getter綁定到一個屬性,有屬性實際上保存一個值

我有example for arrays已經回答了這個。