javascript学习笔录(二)

1、预装图象
function doPreload(){
var the_images = new Array('kwmatt.jpg','matbon.jpg','lunchMat.jpg');
preloadImages(the_images);
}

function preloadImages(the_images_array) {
for(loop = 0; loop < the_images_array.length; loop++){
var an_image = new Image();
an_image.src = the_images_array[loop];
}
}

doPreload()函数创建了需要预装的图象名的数组,并把数组作为参数传送到preloadImages()函数, preloadImages()函数包
含了一个循环,每次循环都创建一个新的图象对象,并把图象名设到它的src属性中。

2、创建一个Javascript对象
(1)、最常见的方法
比如,创建一个宠物
function Pet(the_pet_name, the_form_number){
this.age = 0;
this.hunger = Math.random() * 5; // random number between 0 and 4.99
this.health = Math.random() * 5 + 1 ; // random number between 1 and 3.99
this.happiness = Math.random() * 5;
this.pet_name = the_pet_name;
this.form_number = the_form_number;
window.document.forms[the_form_number].pet_name.value = the_pet_name;
}


这个构造函数有两个参数:宠物名字和要显示其信息的表单号。要创建两个宠物,我们这么
做: 
var pet1 = new Pet("barney",0);
var pet2 = new Pet("betty",1);


(2).工厂方式
     function createobject(){
var o=new Object();
o.a=1;
o.b="w";
o.c=function(){};
return o;
}

当然,你可以给这个函数传入参数进行定制,但是对函数的创建就重复了。
它还有个相近的版本,但是这个版本可以用new来创建
function createobject(){
this.a=1;
this.b="w";
this.c=function(){};
}

(3).使用对象的prototype属性,用一个空构造函数来设置对象名,然后所有的属性和方法都直接用prototype来赋予
function o(){};
o.prototype.a=1;
o.prototype.b=function(){};

此方法也是用new来创建新对象的。

(4).JSON方式来创建
    var o={
a:1,
b:"aa"
c:function(){}
}


3、eval()函数,这个函数可以把一个字符串当作一个JavaScript表达式一样去执行它。
通过eval()函数,可以获取难以索引的对象,代码如下:
function simpleSwap(){
var the_image = prompt("change parrot or cheese","");
var the_image_name = "window.document." + the_image;
var the_image_object = eval(the_image_name);
the_image_object.src = "ant.gif";
}


4、四种手段来设置文本框的文本的简单例子:
如果在一个表单里有一个文本框,象这样:
<form name="the_form">
<input type="text" name="the_text_box">
</form>


JS代码如下所示:
我们可以用四种手段来设置文本框的文本,代码如下:
var the_form_name = "the_form";
var the_element_name = "the_text_box";

(1)、window.document.forms[0].elements[0].value = "hello!";
(2)、window.document.forms[the_form_name].elements[the_element_name].value = "hello!";
(3)、window.document.the_form.the_text_box.value = "hello!";
(4)、var the_element_string = "window.document." + the_form_name + "." + the_element_name;
var the_element = eval(the_element_string);
the_element_string.value = "hello!";


5、常看的JS错误:
[quote]混淆变量名或函数名
偶然地使用了保留字
偶然给变量加上了引号,或忘了给字符串加引号...[/quote]

6、优化JavaScript代码
[quote](1)、限制循环内的工作量
(2)、定制if-then-else语句,按最可能到最不可能的顺序
(3)、最小化重复执行的表达式[/quote]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值