Просмотр полной версии : доступ к свойствам объекта из конструктора
Добрый день =)
Уважаемые товарищи! Есть код:
class Class_1
{
private var _state;
public var _mc:MovieClip;
//конструктор
public function Class_1(mc:MovieClip)
{
_mc = mc;
_state = 123;
mc.onRelease = function()
{
trace(this._state);
}
}
}
когда создаю объект и нажимаю на кнопку, в output выводится
undefined
что свидетельствует о том, что переменная _state не доступна из функции onRelease
Вопрос: как правильно осуществить доступ к переменной _state из ф-ции onRelease.
Спасибо!
dmitriev
18.01.2010, 16:12
mc.onRelease = function()
В 3АС так уже не делают, а делают так:
class Class_1
{
private var _state;
public var _mc:MovieClip;
//конструктор
public function Class_1(mc:MovieClip)
{
_mc = mc;
_state = 123;
mc.addEventListener(MouseEvent.CLICK, clickListener);
}
private function clickListener(event:MouseEvent):void {
trace(_state);
}
}
спасибо
Добавлено через 50 минут
скажите а как это реализовать в AS 2.0 ?
Добавлено через 50 минут
Upd: просьба перенести в соответствующий раздел
Juice_Green
19.01.2010, 08:36
а что просто trace(_state); не выводит в AS2?
если бы выводило я бы не спросил
область видимости в onRelease собственная как оказалось
даже не смотря на то что я её определяю в классе
Используйте делегат :)
В AS2 обработчик вызывается в области видимости того объекта, через который он вызывается.
class ClassA
{
private var _state:Number;
public var _mc:MovieClip;
//конструктор
public function ClassA(mc:MovieClip)
{
super();
this._mc = mc;
this._state = 123;
mc.onRelease = Delegate.create(this, mc_onReleaseDelegate);
}
private function mc_onReleaseDelegate():Void
{
trace(this._state);
}
}
/**
* The Delegate class creates a function wrapper to let you run a function in the context
* of the original object, rather than in the context of the second object, when you pass a
* function from one object to another.
*/
class com.aditall.utils.Delegate extends Object
{
private var _func:Function;
private var _arguments:Array;
private var _scope:Object;
/**
* Constructor. Creates new Delegate instance.
* @param f Function. Function to be converted to a delegate.
* @param args Array. (Optional) The arguments to be passed to the.
* @param obj Object. (Optional) The scope of the delagate.
* delegate when it will be called.
*/
public function Delegate(f:Function, args:Array, obj:Object)
{
super();
this._func = f;
this._arguments = args;
if (obj) this._scope = obj;
}
/**
* Creates a delegate function for a Context object specified in "obj"
* parameter.
* @param obj Object. Context in which to run the function. If no contex specified will
* run in the scope set in the constructor.
* @return Function. A delegate function scoped to the Context object.
*/
public function createDelegate(obj:Object):Function
{
if (!obj) obj = this._scope;
return create(obj, this._func, this._arguments);
}
/**
* Creates a functions wrapper for the original function so that it runs
* in the provided context.
* @param obj Context in which to run the function.
* @param func Function to run.
* @param fargs Array (Optional) of arguments to pass to the function.
*/
public static function create(obj:Object, func:Function, fargs:Array):Function
{
var f:Function = function():Object
{
var target:Object = arguments.callee.target;
var fnc:Function = arguments.callee.func;
var fa:Array = arguments.callee.args;
if (arguments.length) fa = fa.concat(arguments);
return fnc.apply(target, fa);
};
f.target = obj;
f.func = func;
if (fargs) f.args = fargs;
else f.args = [];
return f;
}
/**
* [Readonly]
* The default contex to call createDelegate, (readonly).
*/
public function get scope():Object { return this._scope };
public function set scope(obj:Object):Void { return; };
}
Отыскался :) Прям молодость вспомнил :)
Тут и стандартного хватит из mx.utils
А чем он более стандартный? :)
Тем, что уже имеется в наличии :)
Ну у меня его например нет... :) Но хотя, пожалуй да, у большинства современных пользователей AS2 скорее всего будет именно mx.utils.Delegate.
спасибо
проблему решил
вообще конечно нужно спрыгивать на 3.0
Работает на vBulletin ® версия 3.7.3. Copyright ©2000-2026, Jelsoft Enterprises Ltd. Перевод: zCarot
Copyright © 1999-2008 Flasher.ru. All rights reserved.