- Creating objects using new Object()
There are several ways to create objects in JavaScript, and all of them
have their place. The simplest way is to use the new operator,
specifically, new Object()
:
<script language="javascript" type="text/javascript">
<!--
person = new Object()
person.name = "Tim Scarfe"
person.height = "6Ft"
person.run = function() {
this.state = "running"
this.speed = "4ms^-1"
}
//-->
</script>
We define a custom object "person," then add to it its own properties
and method afterwards. In this case, the custom method merely
initializes
two more properties.
-
Creating objects using Literal Notation
Another inline way of defining an object is via literal notation.
Supported in JavaScript1.2 and above, it's a more robust form of
creating
an object on the fly:
<script language="javascript" type="text/javascript">
<!--
// Object Literals
timObject = {
property1 : "Hello",
property2 : "MmmMMm",
property3 : ["mmm", 2, 3, 6, "kkk"],
method1 : function(){alert("Method had been called" + this.property1)}
};
timObject.method1();
alert(timObject.property3[2]) // will yield 3
var circle = { x : 0, y : 0, radius: 2 } // another example
// nesting is no problem.
var rectangle = {
upperLeft : { x : 2, y : 2 },
lowerRight : { x : 4, y : 4}
}
alert(rectangle.upperLeft.x) // will yield 2
//-->
</script>
Literal notion can contain arrays or arbitrary JavaScript expressions
or values.
While using the new operator or literal notion to create a
custom
object is both simple and logical, the biggest shortcoming is that
the
result is NOT reusable- we cannot easily initialize different
versions of
the created object. For example with the first demonstration
above, if the
person's name is not "Tim Scarfe", we would need to redefine our
entire
object just to accommodate this change.
-
Object Constructor and prototyping
In the world of OOP, the previous ways of defining an object is
too
limiting in many situations. We need a way to create an object
"type" that
can be used multiple times without having to redefine the object
every
time to meet each particular instance's needs. The standard way to
achieve
this is to use the Object Constructor function.
An object constructor is merely a regular JavaScript
function,
so it's
just as robust (ie: define parameters, call other functions etc).
The
difference between the two is that a constructor function is
called via
the new operator (which you'll see below). By basing our object
definition
on the function syntax, we get its robustness as well.
Lets use a real world item "cat" as an example. A property of a
cat may be
its color or name. A method may be to "meeyow". The important
thing to
realize, however is that every cat will have a different name or
even
meeyow noise. To create an object type that accommodates this need
for
flexibility, we'll use an object constructor:
<script language="javascript" type="text/javascript">
<!--
function cat(name) {
this.name = name;
this.talk = function() {
alert( this.name + " say meeow!" )
}
}
cat1 = new cat("felix")
cat1.talk() //alerts "felix says meeow!"
cat2 = new cat("ginger")
cat2.talk() //alerts "ginger says meeow!"
//-->
</script>
Here the function "cat()" is an object constructor, and its properties
and methods are declared inside it by prefixing them with the
keyword
"this." Objects defined using an object constructor are then
instantiated
using the new keyword. Notice how we're able to easily define
multiple
instances of cat, each with its own name- that's the flexibility
object
constructor brings to custom objects. Constructors create the blueprints
for objects, not the object itself.
-
Adding methods to our object using prototype
We saw above how to add a method to our constructor function by
merely
declaring it inside the function. Another approach is through
prototyping,
which is also more popular due to its elegance. Prototype is a
type of
inheritance in JavaScript. We use it when we would like an object
to
inherit a method after it has been defined. Think of prototyping
mentally
as "attaching" a method to an object after it's been defined, in
which all
object instances then instantly share.
Lets extend our original cat() object above with an additional
method
to change the cat's name, using prototype:
<script language="javascript" type="text/javascript">
<!--
cat.prototype.changeName = function(name) {
this.name = name;
}
firstCat = new cat("pursur")
firstCat.changeName("Bill")
firstCat.talk() //alerts "Bill says meeow!"
//-->
</script>
As you can see we merely use the keyword "prototype" immediately
following
the object's name to utilize this functionality. The custom method
changeName() is now shared by all instances of cat.
-
Using
prototype on prebuilt JavaScript objects
Prototyping works on both custom objects and select prebuilt
objects, such as Date() or String. For the later, the general rule
is that
you can prototype any prebuilt object that's initialized with the
"new"
keyword. I'm now going to give you an example of the later, by
adding
additional functionality to the prebuilt Array object of
JavaScript.
IE5 doesn't support the shift() and unshift() methods of Array
that
NS4+ does, so lets prototype them in!
<script language="javascript" type="text/javascript">
<!--
// The shift() and unshift() methods.
if(!Array.prototype.shift) { // if this method does not exist..
Array.prototype.shift = function(){
firstElement = this[0];
this.reverse();
this.length = Math.max(this.length-1,0);
this.reverse();
return firstElement;
}
}
if(!Array.prototype.unshift) { // if this method does not exist..
Array.prototype.unshift = function(){
this.reverse();
for(var i=arguments.length-1;i>=0;i--){
this[this.length]=arguments[i]
}
this.reverse();
return this.length
}
}
//-->
</script>
The possibilities are endless.
相关推荐
这本书《Learning PHP, MySQL and JavaScript with jQuery, CSS and HTML5》是针对初学者介绍几种关键的Web开发语言的入门级教材。在Web开发领域,PHP、MySQL、JavaScript、jQuery、CSS和HTML5是非常重要的技术栈,...
JavaScript developers looking to enhance their web developments skills by learning object-oriented programming. What You Will Learn Get acquainted with the basics of JavaScript language constructs ...
<title>Learning Javascript <p>Hello World! <script type='text/javascript'> // Your script goes here. ``` 将此文件保存为 HTML 文件后,在浏览器中打开即可查看结果。由于 JavaScript 是解释型语言...
目录学分 关于你这个地方对你有用,如果你了解 JavaScript 基础知识不知道任何 OOP 或至少 JavaScript 特定的 OOP 故事有一个小小的世界,里面住着一只狗、一只猫、一个女人、一个男人,有时还有一个猫女。...
Learning Object-Oriented Programming is an easy-to-follow guide full of hands-on examples of solutions to common problems with object-oriented code in Python, JavaScript, and C#. It starts by helping ...
"Learning-oop-master" 文件夹中可能包含了各种 OOP 实例、练习和解决方案,通过这些资源,你可以深入了解 JavaScript 中的面向对象编程,并提升自己的编程技能。实践中,不断尝试创建、继承和封装不同的类,以及...
- JavaScript支持原型继承和类继承两种方式实现OOP。 - 类(class)是ES6中引入的新特性,简化了面向对象编程的过程。 4. **实战篇**: - 本书提供了多个实际项目案例,如构建一个简单的网页游戏、实现一个动态网站...
Learning JavaScript will help you see the broader picture of web development. This book will take your imagination to new heights by teaching you how to work with JavaScript from scratch. It will ...
- JavaScript 支持多种编程范式,包括 OOP 和 FP。 - **函数式编程:** 使用纯函数和不可变数据结构。 - **面向对象编程:** JavaScript 通过原型链实现了面向对象编程。 **作用域的理解:** - **局部作用域:** ...
JavaScript还包含了异步编程的概念,如回调函数、Promise和async/await,这些都是处理非阻塞I/O操作的重要工具。在"learning.js"中,这部分内容可能会详细讲解如何避免回调地狱,以及如何更优雅地处理异步操作。 除...
在本食谱示例中,您将学习Angular(用于构建前端Web应用程序...TypeScript是JavaScript的超集,具有强大的OOP抽象和可编译为JavaScript的强类型系统。 使用Angular,您可以使用强大的工具和设计模式来构建小型或大型Web
2. `src`目录:存放源代码,包括JavaScript文件,这些文件展示了如何用实际代码实现OOP。 3. `examples`目录:包含各种示例,让你通过实践来学习OOP。 4. `assets`目录:可能存储图片、音频或视频资源,用于增强教程...
8. **持续集成/持续部署(CI/CD)**:学习平台可能还会涉及Jenkins、Travis CI或CircleCI等工具,帮助开发者实现自动化测试和应用部署。 通过【learning_platform】的学习,无论是对Ruby感兴趣的新手,还是寻求提升的...
在这个场景下,可能是使用Python、JavaScript或其他支持OOP的编程语言编写了一个脚本,该脚本能遍历Google云端硬盘和本地文件夹,找出指定类型的文件,然后根据预设规则(如文件名、文件类型等)将它们上传到Moodle...
类是面向对象编程的基础,TypeScript支持ES6中的类语法,允许我们定义类、继承、构造函数以及访问修饰符,提供了更丰富的OOP特性。 5. **模块(Modules)** TypeScript引入了模块系统,可以使用import和export...
它使用现代JavaScript或TypeScript(保留与纯JavaScript的兼容性),并结合OOP(面向对象编程),FP(函数式编程)和FRP(函数响应式编程)的元素。 在宽敞,Nest使用了 ,但也提供了与其他各种库的兼容,例如 ,...
2. **面向对象编程**:与Ruby和JavaScript不同,Java是一种严格的面向对象编程(OOP)语言。这意味着所有程序都由类和对象组成,每个对象都有其属性和行为。Java支持封装、继承和多态这三大面向对象特性。 3. **...
4. **类与对象**:PHP支持面向对象编程(OOP),包括类的定义(`class MyClass { ... }`)、属性(成员变量)和方法(成员函数)。你可以使用`new`关键字实例化对象,并通过`.`操作符调用对象的方法。了解`__...