AS1中的一点点面向对象编程
在我们转移到AS2之前先让我了解一下在AS1时的面向对象的编程。这一节对于在FLASH5和FLASHMX不太了解面向对编程的人来说很重要。假如你已经很了解这些可以直接跳过此节。
尽管AS1不是真正的面向对象的编程语言,开发人员已经在有些时候使用它进行面向对象的编程了。AS1中的任何东西都是依靠原型链也就是对象之间的联系。所以在AS1中使用面向对象需要了解原型链(或者是原型的要害字)。
AS1的类就象是规则的函数。方法附加在这个的类的原型上。例如:
// Wizard class
function Wizard() {
}// help()方法附加在WIZARD函数的原型上。 Wizard.prototype.help = function() { };假如我们把help()直接放在wizard class类中。FLASH在查找属性和方法时就不会找到它,因为FLASH在查找是沿着原型链进行搜索的。而在为所有的Wizard类创建一个实例copy.下面就是为每个实例创建的copy.function Wizard(){this.help=function(){}}对于java,c#的程序员来说。这样的将方法代码放在类中会看来很熟悉,然而为了代码的可重用性我们还是应将方法附加在类的原型链上。在下面的例子中假如我们针对一个类上有两个方法,一个是附加在原型链上,另一个是直接放在类中,flash将先获得内部方法。// AS1_OOP_01.fla function TestClass() { this.method = function() { trace("Internal method"); };
this.prop = ">>> Internal prop"; }// Attach a method to the prototype object of the class TestClass.prototype.method = function() { trace("Prototype method"); };TestClass.prototype.prop = ">>> Prototype prop";// Create an instance of the TestClass class var w = new TestClass();// Internal method is located before the prototype method w.method();// Replace the Internal method w.method = function() { trace("New method"); }; w.method();// Delete the Internal method delete w.method;// The only method remaining is the prototype method w.method();// Test the properties trace(w.prop);w.prop = ">>> New prop"; trace(w.prop);delete w.prop; trace(w.prop);
评论加载中…
![]() |