![]() |
|
||||||||||
|
|||||||
|
|
« Предыдущая тема | Следующая тема » |
| Опции темы | Опции просмотра |
|
![]() |
![]() |
|
|||||
|
Регистрация: Feb 2008
Сообщений: 890
|
Пример-программа из библии по AS2.0, где генерируются мерцающие буквы в случайном месте сцены. В среде авторских работ создается динамическое текстовое поле, куда монтируется несколько букв определенного шрифта для дальнейшего программного доступа к ним.
Далее пишется следующий код: function displayLetter():Void {
// Create a random integer to yield one of the indices from the
// aLetters array.
var nRandomIndex:Number = Math.ceil(Math.random() * aLetters.length) - 1;
// Create random numbers to use for the x and y coordinates of the
// letter TextField.
var nRandomX:Number = Math.random() * 550;
var nRandomY:Number = Math.random() * 400;
// Get the next available depth;
var nDepth:Number = this.getNextHighestDepth();
// Create a new TextField object at the random x and y coordinates.
this.createTextField("tLetter" + nDepth, nDepth, nRandomX, nRandomY, 0, 0);
// Assign a reference to a variable to make it more convenient to
// work with the TextField.
var tLetter:TextField = this["tLetter" + nDepth];
// Set the autoSize and text properties so the random letter
// displays.
tLetter.autoSize = "left";
tLetter.text = aLetters[nRandomIndex];
// Set a custom property called fadeDirection that determines
// the increment by which the alpha will change. And set the
// alpha to 0 initially.
tLetter.fadeDirection = 5;
tLetter._alpha = 0;
// Tell Flash to embed the font for the TextField.
tLetter.embedFonts = true;
// Create a TextFormat object that tells Flash to use the
// Verdana font and set the size to 15.
var tfFormatter:TextFormat = new TextFormat();
tfFormatter.font = "Verdana";
tfFormatter.size = 15;
// Assign the TextFormat to the TextField.
tLetter.setTextFormat(tfFormatter);
// Set an interval at which the letter will fade in and out.
tLetter.nInterval = setInterval(this, "alphaFade", 10, tLetter);
}
function alphaFade(tLetter:TextField):Void {
// Increment the letter TextField's alpha.
tLetter._alpha += tLetter.fadeDirection;
// Check to see if the letter has faded in completely. If so
// set the fadeDirection property to -5 so that the TextField
// starts to fade out. Otherwise, if the letter has faded out
// completely...
if(tLetter.fadeDirection > 0 && tLetter._alpha >= 100) {
tLetter.fadeDirection = -5;
}
else if(tLetter.fadeDirection < 0 && tLetter._alpha <= 0) {
// ... clear the interval and remove the TextField.
clearInterval(tLetter.nInterval);
tLetter.removeTextField();
}
// Make sure to update the screen.
updateAfterEvent();
}
// Create the array of letters.
var aLetters:Array = ["a", "b", "c", "d", "e", "f"];
// Set the interval at which a new letter should be displayed.
var nDisplayInterval:Number = setInterval(this, "displayLetter", 1);
- выдает undefined. Стал искать серьезные отличии в кодах и увидел, что у меня запуск интервальных функций инициализирован не tLetter.nInterval = setInterval(this, "alphaFade", 10, tLetter); var nDisplayInterval:Number = setInterval(this, "displayLetter", 1); tLetter.nInterval = setInterval(alphaFade, 10, tLetter); var nDisplayInterval:Number = setInterval(displayLetter, 1); Т.е. в книге говорится, что синтаксис запуска функций: setInterval(functionName, interval, params ); объектных методов: setInterval(objectName, "objectMethod", interval, params); Посмотрел мануал, действительно, есть синтаксис setInterval(this, "functionName", interval, params); - я так понимаю, что он идентичен синтаксису setInterval(functionName, interval, params );, но почему же тогда при синтаксисе через this все работает, а при другом нет? Объясните разницу, если она есть, плиз. Извините, что так много букв...))) Последний раз редактировалось orcpochta; 30.05.2008 в 14:22. |
|
|||||
|
Все упирается в область видимости имен. Если в функции displayLetter () есть ссылка с помощью this, то в методе setInterval () эта ссылка даст другое значение. Когда используешь такую сигнатуру:
То сам задаешь область видимости функции. Последний раз редактировалось Волгоградец; 30.05.2008 в 13:38. |
|
|||||
|
Регистрация: Feb 2008
Сообщений: 890
|
Извините, ничего не понял..((
|
|
|||||
|
|
|
|||||
|
Регистрация: May 2008
Сообщений: 476
|
Если Вы проанализируете работу вот этого кода то поймете почему.
|
|
|||||
|
Регистрация: Feb 2008
Сообщений: 890
|
я примерно понял, но осталось уяснить какую роль играет this в самом первом вызове интервальной функции var nDisplayInterval:Number = setInterval(this, "displayLetter", 1); - чем this там является?
Цитата:
опять же тут все ясно: создается объект, ему присваивается метод, который затем и вызывается в интервале - но это никак меня не приблизило к пониманию моего вопроса..)) Последний раз редактировалось alexcon314; 01.06.2008 в 23:57. |
|
|||||
|
Регистрация: May 2008
Сообщений: 476
|
Виноват, исправляюсь! Сильно торопился Вам помочь, что даже ненаписал var.
![]() |
|
|||||
|
Если здесь
опустить слово this, то получится вот что: вот эта строчка не будет работать, т.к. в этом случае слово this будет относиться к методу setInterval (), т.е. для компилятора строчка будет выглядеть как А т.к. у setInterval нет такого метода, то и появляется ошибка. |
|
|||||
|
Регистрация: Feb 2008
Сообщений: 890
|
Спасибо! Разобрался..))
|
|
|||||
|
Et cetera
Регистрация: Sep 2002
Сообщений: 30,787
|
Цитата:
|
![]() |
![]() |
Часовой пояс GMT +4, время: 10:37. |
|
|
« Предыдущая тема | Следующая тема » |
|
|