SORU
11 EYLÜL 2008, PERŞEMBE


JavaScript özel yöntemler

Genel bir yöntem JavaScript ile bir sınıf yapmak için bir şey gibi yapardım:

function Restaurant()
{
}

Restaurant.prototype.buy_food = function()
{
   // something here
}

Restaurant.prototype.use_restroom = function()
{
   // something here
}

Sınıfımdan kullanıcısı olabilir:

var restaurant = new Restaurant();
restaurant.buy_food();
restaurant.use_restroom();

Nasıl kamu buy_food ve use_restroom benim yöntemleri çağırabilir ama sınıf kullanıcılar dışarıdan arayamaz özel bir yöntem oluştururum.

Diğer bir deyişle, yapmak için yöntem çok başarmak istiyorum:

Restaurant.prototype.use_restroom = function()
{
   this.private_stuff();
}

Ama bu iş olmamalı:

var r = new Restaurant();
r.private_stuff();

Nasıl ikisi de doğru tutun çok özel bir yöntem olarak private_stuff tanımlayabilirim?

Doug Crockford's writeup birkaç kez ama" yöntemleri genel yöntemler ve "ayrıcalıklı" yöntemleri dışarıdan çağrılabilir. çağrılabilir "özel benzemiyor okudum

CEVAP
11 EYLÜL 2008, PERŞEMBE


Bunu yapabilirsin, ancak olumsuz prototip bir parçası olamaz

function Restaurant()
{
    var myPrivateVar;

    var private_stuff = function()   // Only visible inside Restaurant()
    {
        myPrivateVar = "I can set this here!";
    }

    this.use_restroom = function()   // use_restroom is visible to all
    {
        private_stuff();
    }

    this.buy_food = function()    // buy_food is visible to all
    {
        private_stuff();
    }
}

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • calicoJake

    calicoJake

    29 EKİM 2007
  • Helen Bradley

    Helen Bradle

    4 Mart 2008
  • Richard Laxa

    Richard Laxa

    30 AĞUSTOS 2012