2013-03-05 91 views
0

我正在尋找一個完美的方式來定義類。這裏的「完美」表示:`在javascript中,是否有完美的方式來定義類

  1. 創建實例不會創建方法的副本。
  2. 公共功能可以很容易地(不太多的麻煩)訪問私有變量

例如,方式1:

function Foo1() { 
    var private1; 
    this.publicMethod1 = function() {//create instance will create copy of this function} 
} 

將不符合上述規則第一。

又如,方法2:

function Foo2() { 
     var private2; 

    } 
Foo2.prototype.Method2 = function() {//cannot access private2} 

會不適應上述規則2號。

那麼是否可以同時滿足這兩個規則?謝謝。

回答

0
function Foo3() { 
    this.private = {}; 
} 

Foo3.prototype.set_x = function (x) { 
    this.private.x = x; 
}; 
+0

準確地說,在這種情況下,您的字段「private」仍然是公開的。 – 2013-03-05 06:53:27

+0

@ Chips_100是的,但這不是要求的一部分。 – melpomene 2013-03-05 06:54:09

0

長話短說:不,它不是。您無法使用可訪問private變量的方法來擴展原型。至少如果這些私有變量通過closure私有變量。

儘管如此,JavaScript中的慣例是用下劃線標記私有字段,例如_myPrivateField。這些仍然是公開的,但我已經看到這個解決方案正在許多圖書館使用,我也更喜歡這種風格來滿足你的第一條規則。

+0

是否有關閉的方式使其工作?謝謝 – 2013-03-05 07:02:05

1

在JavaScript中,它更多的是約定。首先使用下劃線來定義私有屬性或方法,如_private。有了幾個助手,你可以輕鬆地上課。我覺得這個設置很容易的,你需要的是一個輔助inherits擴展類,而不是使用多個參數,你在一個對象props通過,並只需撥打「超級」在繼承的類與arguments。例如,使用一個模塊的模式:需要的一切祕密的進行

Function.prototype.inherits = function(parent) { 
    this.prototype = Object.create(parent.prototype); 
}; 

var Person = (function PersonClass() { 

    function Person(props) { 
    this.name = props.name || 'unnamed'; 
    this.age = props.age || 0; 
    } 

    Person.prototype = { 
    say: function() { 
     return 'My name is '+ this.name +'. I am '+ this.age +' years old.'; 
    } 
    }; 

    return Person; 

}()); 

var Student = (function StudentClass(_super) { 

    Student.inherits(_super);  

    function Student(props) { 
    _super.apply(this, arguments); 
    this.grade = props.grade || 'untested'; 
    } 

    Student.prototype.say = function() { 
    return 'My grade is '+ this.grade +'.'; 
    }; 

    return Student; 

}(Person)); 

var john = new Student({ 
    name: 'John', 
    age: 25, 
    grade: 'A+' 
}); 

console.log(JSON.stringify(john)); //=> {"name":"John","age":25,"grade":"A+"} 
console.log(john.say()); //=> "My grade is A+" 

關於私有變量「問題」只是堅持約定實例的屬性和使用閉。

0

一個基本的例子如下:

Foo = function(id) 
{ 
    // private instances. 
    var _id; 
    var _self = this; 

    // constructor 
    _id = id; 

    // private method 
    function _get() 
    { 
     return _id; 
    }; 

    // public function 
    _self.set = function(id) 
    { 
     _id = id; 
    }; 
    _self.get = function() 
    { 
     return _get(); 
    }; 
}; 

var bar = Foo(100); 
console.log(bar.get()); 
bar.set(1000); 
console.log(bar.get()); 

我會建議你使用prototype

相關問題