For*_*ood 4 javascript object actionscript-3
由于actionscript 3.0基于ECMAscript,它与javascript有一些相似之处.我一直在玩的一个这样的相似之处是从函数创建对象.
在javascript中创建一个对象,
var student = new Student( 33 );
document.write( student.age );
function Student( age ){
this.age = age;
}
Run Code Online (Sandbox Code Playgroud)
在actionscript 3.0中,对象通常是通过类创建的,但可以通过构造函数在javascript中创建对象.
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var student = new Student( 33 );
trace( student.age );
}
}
}
function Student( age ) {
this.age = age;
}
Run Code Online (Sandbox Code Playgroud)
但是我用上面的代码得到了一个编译错误
Loading configuration file C:\Program Files\Adobe\Flex Builder 3\sdks\3.1.0\frameworks\flex-config.xml
C:\Documents and Settings\mallen\Desktop\as3\Main.as(5): col: 23 Error: Incorrect number of arguments. Expected 0
var student = new Student( 33 );
^
我想知道为什么会这样?为了使事情变得更加奇怪,以下代码确实有用
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
Student( 33 );
var student = new Student();
trace(student.age);
/* When I add the two lines below, the code wont compile? */
//var student2 = new Student( 33 );
//trace(student2.age);
}
}
}
function Student( age ){
this.age = age;
trace(age);
}
Run Code Online (Sandbox Code Playgroud)
此代码的输出是
33 undefined undefined
从语法上讲,这是两个分歧的区域(在众多区域中).;)
您可以使用函数创建对象:
private var studentName:String = "Joe";
private function init():void
{
var s = new Student("Chris");
trace(s.studentName);
trace(this.studentName);
trace(typeof s);
trace(typeof Student);
s.sayHi();
trace("Hello, " + s.studentName + ". I'm " + studentName + ".");
}
var Student:Function = function(studentName:String):void
{
this.studentName = studentName;
this.sayHi = function():void
{
trace("Hi! I'm " + this.studentName + ".");
};
};
// Chris
// Joe
// object
// function
// Hi! I'm Chris.
// Hello, Chris. I'm Joe.
Run Code Online (Sandbox Code Playgroud)
......只是略有不同的语法.Function类也是动态的,这意味着您可以在运行时将方法移植到其实例上(就像我上面使用sayHi()),就像使用JavaScript的"prototype"属性一样.
我实际上不确定是什么样的烦恼,命名冲突,奇怪等等,你可能会遇到这种方法,因为我还没有深入研究它的文档 - 但它确实有效!
| 归档时间: |
|
| 查看次数: |
2473 次 |
| 最近记录: |