JavaScript 对象基础:属性与方法详解

作者:青柠时间:2026-10-24 13:52:41浏览:639

本文介绍JavaScript作为面向对象编程语言的基础,重点解析内置对象的属性与方法。通过String对象的length属性和toUpperCase()方法示例,展示如何获取字符串长度及转换大小写,帮助初学者理解对象数据与行为的基本用法。

JavaScript 对象基础:属性与方法详解

JavaScript is an Object Oriented Programming (OOP) language. JS是面向对象编程(Object Oriented Programming)语言。 (注:此处涉及基于对象与面向对象的区分,建议读者自行查阅相关资料以明确概念)。 An OOP language allows you to define your own objects and make your own variable types. 面向对象语言允许用户自定义对象并创建自定义变量类型。 -------------------------------------------------------------------------------- Object Oriented Programming (面向对象编程) JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your own objects and make your own variable types. JavaScript 属于面向对象编程(OOP)语言,该类语言支持定义自定义对象及变量类型。(注:此段内容与上文存在重复)。 However, creating your own objects will be explained later, in the Advanced JavaScript section. We will start by looking at the built-in JavaScript objects, and how they are used. The next pages will explain each built-in JavaScript object in detail. 然而,关于自定义对象的创建将在后续“高级 JavaScript”章节中进行讲解。本文档首先介绍内置的 JavaScript 对象及其用法,后续页面将逐一详细解析每个内置对象。 Note that an object is just a special kind of data. An object has properties and methods. 请注意,对象本质上是一种特殊类型的数据。对象包含属性(properties)和方法(methods)。 -------------------------------------------------------------------------------- Properties (属性) Properties are the values associated with an object. 属性是与对象相关联的值。 In the following example we are using the length property of the String object to return the number of characters in a string: 在以下示例中,我们使用 String 对象的 length 属性来返回字符串中的字符数量: <script type="text/javascript"> var txt="Hello World!" document.write(txt.length) </script> The output of the code above will be: 上述代码的输出结果为: 12 -------------------------------------------------------------------------------- Methods (方法) Methods are the actions that can be performed on objects. 方法是可在对象上执行的操作。 In the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters: 在以下示例中,我们使用 String 对象的 toUpperCase() 方法将文本转换为大写形式显示: <script type="text/javascript"> var str="Hello world!" document.write(str.toUpperCase()) </script> The output of the code above will be: 上述代码的输出结果为: HELLO WORLD!

作者最新文章