原创转载请注明出处:http://agilestyle.iteye.com/blog/2341782
The this Object
Every scope in JavaScript has a this object that represents the calling object for the function. In the global scope, this represents the global object (window in web browsers). When a function is called while attached to an object, the value of this is equal to that object by default. So, instead of directly referencing an object inside a method, you can reference this instead. For example:
var person = { name: "Michael", sayName: function () { console.log(this.name); } }; person.sayName(); // outputs "Michael"
You can easily change the name of the variable or even reuse the function on different objects.
function sayNameForAll() { console.log(this.name); } var person1 = { name: "Michael", sayName: sayNameForAll }; var person2 = { name: "Kobe", sayName: sayNameForAll }; var name = "David"; person1.sayName(); // outputs "Micheal" person2.sayName(); // outputs "Kobe" sayNameForAll(); // outputs "David"
The ability to use and manipulate the this value of functions is key to good object-oriented programming in JavaScript. Functions can be used in many different contexts, and they need to be able to work in each situation. Even though this is typically assigned automatically, you can change its value to achieve different goals. There are three function methods that allow you to change the value of this. (Remember that functions are objects, and objects can have methods, so functions can, too.)
The call() Method
The first function method for manipulating this is call(), which executes the function with a particular this value and with specific parameters. The first parameter of call() is the value to which this should be equal when the function is executed. All subsequent parameters are the parameters that should be passed into the function. For example:
function sayNameForAll(label) { console.log(label + ":" + this.name); } var person1 = { name: "Michael" }; var person2 = { name: "Kobe" }; var name = "David"; sayNameForAll.call(this, "global"); // outputs "global:Michael" sayNameForAll.call(person1, "person1"); // outputs "person1:Kobe" sayNameForAll.call(person2, "person2"); // outputs "person2:David"
The apply() Method
The second function method you can use to manipulate this is apply(). The apply() method works exactly the same as call() except that it accepts only two parameters: the value for this and an array or array-like object of parameters to pass to the function (that means you can use an arguments object as the second parameter). So, instead of individually naming each parameter using call(), you can easily pass arrays to apply() as the second argument. Otherwise, call() and apply() behave identically. For example:
function sayNameForAll(label) { console.log(label + ":" + this.name); } var person1 = { name: "Michael" }; var person2 = { name: "Kobe" }; var name = "David"; sayNameForAll.apply(this, ["global"]); // outputs "global:Michael" sayNameForAll.apply(person1, ["person1"]); // outputs "person1:Kobe" sayNameForAll.apply(person2, ["person2"]); // outputs "person2:David"
Note:
The method you use typically depends on the type of data you have. If you already have an array of data, use apply(); if you just have individual variables, use call().
The bind() Method
The third function method for changing this is bind(). This method was added in ECMAScript 5, and it behaves quite differently than the other two. The first argument to bind() is the this value for the new function. All other arguments represent named parameters that should be permanently set in the new function. You can still pass in any parameters that aren't permanently set later.
The following code shows two examples that use bind(). You create the sayNameForPerson1() function by binding the this value to person1, while sayNameForPerson2() binds this to person2 and binds the first parameter as "person2".
function sayNameForAll(label) { console.log(label + ":" + this.name); } var person1 = { name: "Michael" }; var person2 = { name: "Kobe" }; // create a function just for person1 var sayNameForPerson1 = sayNameForAll.bind(person1); sayNameForPerson1("person1"); // outputs "person1:Michael" // create a function just for person2 var sayNameForPerson2 = sayNameForAll.bind(person2, "person2"); sayNameForPerson2(); // outputs "person2:Kobe" // attaching a method to an object doesn't change 'this' person2.sayName = sayNameForPerson1; person2.sayName("person2"); // outputs "person2:Michael"
No parameters are bound for sayNameForPerson1(), so you still need to pass in the label for the output. The function sayNameForPerson2() not only binds this to person2 but also binds the first parameter as "person2". That means you can call sayNameForPerson2() without passing in any additional arguments. The last part of this example adds sayNameForPerson1() onto person2 with the name sayName. The function is bound, so the value of this doesn’t change even though sayNameForPerson1 is now a function on person2. The method still outputs the value of person1.name.
Reference
Leanpub.Principles.of.Object-Oriented.Programming.in.JavaScript.Jun.2014
相关推荐
Mastering JavaScript Object-Oriented Programming 2016 | ISBN: 1785889109 | English | 287 pages | PDF | 1.9 MB With this book, we'll provide you with a comprehensive overview of OOP principles in ...
npm install immutable-object-methods --save用法import { getIn , setIn , mergeDeep , assign , set , without , chain } from 'immutable-object-methods' ;const input = { a : { b : 'c' } } ;const updated ...
Learn the basics of JavaScript programming: functions, methods, properties, loops and logic Use events to track user interactions Build smarter web forms that improve the user experience Work with...
The book then rounds off with an overview of methods to effectively use and mix functional programming with object-oriented programming. Table of Contents Chapter 1. The Powers of JavaScript's ...
`Object_methods`可能指的是与JavaScript中的`Object`对象相关的各种内置方法。在本篇文章中,我们将深入探讨这些方法,包括它们的功能、用法以及如何在实际编程中应用。 1. `Object.create()`: 这个方法创建一个新...
JavaScript is an object-oriented scripting language that enables you to modify a document’s structure, styling, and content in response to user actions. This handy pocket serves as both a quick ...
“Scriptable properties and methods”则详细列出了所有可脚本化的属性和方法,以便于开发者进行更高级的操作;此外,还提到了错误处理(“Errormessages”)和编码支持(“Supported encoding names”),这些都是...
* Objects, * Functions, * Inheritance, * Arrays, * Regular expressions, * Methods, * Style, * Beautiful features, Appendices summarize JavaScript's bad parts and awful parts. But the greatest benefit...
在JavaScript中,`Object.create()`方法是一个非常重要的构造机制,它允许我们创建一个新的对象,并将该新对象的原型设置为传入的第一个参数。这在面向对象编程中特别有用,因为原型是JavaScript实现继承的核心概念...
3. **数组方法(Array Methods)**:5.5版本中,数组对象新增了多种实用的方法,如`forEach()`、`map()`、`filter()`、`reduce()`等,这些方法提供了更便捷的数组操作方式,使得处理数组数据更为高效。 4. **对象...
6. Math对象和全局对象(The Math object and The global object):讲解了JavaScript中的Math对象提供的数学操作以及全局对象的作用。 7. 高阶函数(Higher-Order Functions):介绍抽象化(Abstraction)、抽象化...
对象是数据和函数的集合,通过属性(properties)和方法(methods)来访问和操作。JavaScript有内置对象(如Date、Math)、宿主对象(如window)以及自定义对象。对象可以通过字面量语法或者构造函数来创建,而原型...
JavaScript是一种广泛应用于网页和网络应用开发的脚本语言,它主要负责实现...在压缩包的文件中,如script.htm、methods.html、objects.html等,很可能包含了对这些知识点的具体讲解和示例,是学习JavaScript的好资源。
"Object Oriented JavaScript"是OOP在JavaScript中的应用。在"Introduction"中,作者对比了传统的类式继承与JavaScript的原型链机制。JavaScript中的"Objects and Classes vs. Prototype Classes"揭示了其独特的继承...
6.10 Object Methods 138 7. Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 7.1 Creating Arrays 141 7.2 Reading ...
这意味着在JavaScript中,对象被视为存储数据的一种大型数组形式,其中每个对象都有一个属性列表,包含该对象的所有属性(attributes)和方法(methods)。简而言之,可以将JavaScript对象视为一个包含键值对的容器...
This is a fast-paced guide that will help you to write real-... The book then rounds off with an overview of methods to effectively use and mix functional programming with object-oriented programming.
### JavaScript入门教程:深入了解面向对象编程 #### 一、JavaScript:一种基于原型的语言 JavaScript 是一种灵活且功能强大的脚本语言,广泛应用于网页开发中。它不仅能够处理简单的任务,如响应用户事件或操作...