您的位置:首页 > Web前端 > JavaScript

[Javascript入门]Javascript之初体验3

2013-08-14 17:34 204 查看
//JavaScript 中的所有事物都是对象:字符串、数值、数组、函数等等,并且允许自定义对象。

//对象只是带有属性和方法的特殊数据类型

/*访问对象属性:

属性是与对象相关的值。

访问对象属性的语法是:objectName.propertyName*/

/*访问对象的方法

方法是能够在对象上执行的动作。

通过以下语法来调用方法:objectName.methodName()*/

/*创建 JavaScript 对象

通过 JavaScript,您能够定义并创建自己的对象。

创建新对象有两种不同的方法:

1.定义并创建对象的实例

2.使用函数来定义对象,然后创建新的对象实例

*/

person=new Object();

person.firstname="Bill";

person.lastname="Gates";

person.age=56;

person.eyecolor="blue";

person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};

//使用对象构造器

//有了对象构造器,就可以创建新的对象实例

<!DOCTYPE html>

<html>

<body>

<script>

function person(firstname,lastname,age,eyecolor)

{

this.firstname=firstname;

this.lastname=lastname;

this.age=age;

this.eyecolor=eyecolor;

}

myFather=new person("Bill","Gates",56,"blue");

document.write(myFather.firstname + " is " + myFather.age + " years old.");

</script>

</body>

</html>

//把方法添加到 JavaScript 对象 方法只不过是附加在对象上的函数。

//在构造器函数内部定义对象的方法:

<!DOCTYPE html>

<html>

<body>

<script>

function person(firstname,lastname,age,eyecolor)

{

this.firstname=firstname;

this.lastname=lastname;

this.age=age;

this.eyecolor=eyecolor;

 

this.changeName=changeName;

function changeName(name)

{

this.lastname=name;

}

}

myMother=new person("Steve","Jobs",56,"green");

myMother.changeName("Ballmer");

document.write(myMother.lastname);

</script>

</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: