![]() |
![]() |
JavaScript高级教程 - 第四课 | |
Thau |
|
第六页:创建你自己的对象 对象的概念使你能够以一种更易理解的方式去组织你的信息。让
为了这个练习,让我们先不管如何把现代资本主义社会工人进行
要创建你自己的对象,你需要从模板开始。在面向对象编程中模 var fred = new Employee("Fred Flintstone", 33, "Surface Miner", 20000); var barney = new Employee("Barney Rubble", 33, "Slacker", 40000); var boss = new Employee("Mr. Slate",50, "CEO", 1000000); 如果这几个实例已被创建,你可以做这些事情: barney.promotion("Chief Slacker","10"); fred.fired(); boss.vacation(365);
这样就把Barney提升为‘首席懒鬼’并增加10%的薪水,炒掉
当然你得自己从属性开始编写对象构造器和方法,这里是雇员的 function Employee(name, age, title, salary) { this.name = name; this.age = age; this.title = title; this.salary = salary; }
请注意构造器其实就是一个函数。在函数中我们需要给
你可以给构造函数传递参数
,当象下面这个语句这样调用构造函 ... 然后在构造函数中的这条语句: this.name = name;
... 我们就把这个雇员的名字设成了传递给雇员构造函数的参数
构造函数中使用的 "this"
关键字的原因是你可能一次创建多个雇
方法只不过是加在对象上的函数。首先定义函数,然后把函数加 function promotion(new_title,percent_raise) { var salary_increase = this.salary * percent_raise; this.salary = this.salary + salary_increase; this.title = new_title; }
这个函数计算雇员的新工资并把新工资和新职位赋给雇员。 barney.promotion("Chief Slacker",10);
那 "this"就是指
is Barney. 这看起来确实有一点怪异,可能要
创建对象的最后一步就是把方法连到对象上。我刚才提到了,你 this.promotion = promotion; 下面是增加了提升方法的构造函数: function Employee(name, age, title, salary) { this.name = name; this.age = age; this.title = title; this.salary = salary; this.promotion = promotion; } function promotion(new_title,percent_raise) { var salary_increase = this.salary * percent_raise; this.salary = this.salary + salary_increase; this.title = new_title; }
如要增加其它信息,比如雇员的办公室,可以增加一个名为
明白了吗? 现在来看看更复杂和重要的面向对象的JavaScript, 去 JavaScript高级教程 本栏目内容归Wired Digital Inc.所有,任何单位或个人未经许可,不得擅自转载使用。 搜狐公司制作完成。 |
||||||||||||||||