Home >Web Front-end >JS Tutorial >Dynamic this and dynamic binding example code under javascript_javascript skills

Dynamic this and dynamic binding example code under javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:37:071162browse

Then the function is divided into two parts and stored in the object. One is its function name (key), and the other is the function body (value). Then this in the function generally points to the object where the function is located. But this is just general. When calling a function globally, we do not see the caller, or it is the window at this time. However, after the function is declared, it is not actually bound to any object, so we can use call apply methods to set the caller.

A simple example:
[script]
<script> <br>window.name = "window"; <br>var run = function() { <br>alert( "My name is " this.name); <br>} <br>run(); <br></script>
[/html]
Here you cannot say that run is an attribute of window exists, but it is indeed called by the window property. In fact, most of the things exposed at the top are taken over by the window. When they need to be called, they are copied to the window object (but window does not inherit the object in IE), so there is a performance difference between window['xxx'] and window.xxx. This is an internal implementation, so I won’t delve into it further.
Another example, binding to an explicit object


[Ctrl A Select all Note: If you need to introduce external Js, you need to refresh to execute
]

The answer is obviously easy to see, this Always for its caller. But what if it’s a little more complicated?

[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
]
Although it is defined in object Internally, although it is defined inside the run function, what it pops up is neither object nor run, because it is neither an attribute of object nor an attribute of run. It is loosely used in the scope of run and cannot be called by the first two, so it can only be saved by window. Native objects such as window are permeated inside all scripts and are pervasive. Wherever they are needed to contribute, they are obligated. But usually we don't need it to help, so we need to develop two powerful tools: call and apply.
[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh it to execute
]


[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute Copy the code


The code is as follows:


var bind = function(context, fn) {
return function() {
return fn.apply(context, arguments);
}
}


[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute ] But in order to face more complexities In this case, it is recommended to use the following version.
<script> window.name = "window"; object = { name: "object", run: function() { alert("My name is " + this.name); } }; object.run(); </script>Copy code<script> window.name = "window"; object = { name: "object", run: function() { var inner = function(){ alert("My name is " + this.name); } inner(); } }; object.run(); </script><script> window.name = "window"; var object = { name: "object", run: function() { inner = function() { alert( this.name); } inner.call(this); } } object.run(); </script><script> window.name = "Window"; var cat = { name: "Cat" }; var dog = { name: "Dog", sound: function(word) { alert(this.name + word); } }; dog.sound(" is pooping"); dog.sound.call(window, " is banking"); dog.sound.call(dog, " is banking"); dog.sound.apply(cat, [" miaowing"]); </script> The code is as follows:<script> window.name = "Window"; var cat = { name: "Cat" }; var dog = { name: "Dog", sound: function(word) { alert(this.name + word); } }; var bind = function(context, fn) { return function() { return fn.apply(context, arguments); } } var sound2 = bind(window,dog.sound); sound2(" is banking"); var sound3 = bind(cat,dog.sound); sound3(" miaowing") </script>

function bind(context,fn) {
var args = Array.prototype.slice.call(arguments, 2);
return args.length == 0 ? function() {
return fn.apply(context, arguments);
} : function() {
return fn.apply(context, args.concat.apply(args, arguments));
};
};

它还有一个孪生兄弟叫bindAsEventListener ,绑定事件对象,没什么好说的。
复制代码 代码如下:

var bindAsEventListener = function(context, fn) {
return function(e) {
return fn.call(context, (e|| window.event));
}
}

Prototype的版本
复制代码 代码如下:

Function.prototype.bind = function() {
if (arguments.length < 2 && (typeof arguments[0]==='undefined'))
return this;
var _slice = Array.prototype.slice
var __method = this, args = _slice.call(arguments,0), context = args.shift();
return function() {
return __method.apply(context, args.concat(_slice.call(arguments,0)));
}
}


[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]

bind函数是如此有用,google早早已把它加入到Function的原型中了(此外还有inherits,mixin与partial)。
复制代码 代码如下:

//在chrome中
var a = function(){};
alert(a.bind)

有绑定就有反绑定,或者叫剥离更好!例如原生对象的泛化方法我们是无法通过遍历取出它们的。

[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]

要取出它们就需要这个东西:
复制代码 代码如下:

var _slice = Array.prototype.slice;
function unbind(fn) {//第一步取得泛化方法
return function(context) {//第二部用对应原生对象去重新调用!
return fn.apply(context, _slice.call(arguments, 1));
};
};

Examples have been given before, please see Article
Summary:
The value of this depends on the way the function is called, there are four types in total,
If a function is A property of an object. When the function is called, the value of this is this object. If the expression called by function contains a period (.) or [], the value of this is the object before the period (.) or []. For example, in myObj.func and myObj["func"], this is myObj when func is called.
If a function is not a property of an object, then when the function is called, the value of this is the global object. When a function contains an internal function, it is easy to cause errors if you do not understand the correct meaning of this. This is because the this value of the inner function is different from the this value of its outer function. The solution is to save the outer function's this value in a variable and use it in the inner function to look up the variable.
If new is used before a function, a new object will be created, the function will also be called, and the value of this is the newly created object. For example, in function User(name) {this.name = name}; var user1 = new User("Alex");, by calling new User("Alex"), a new object will be created, referenced by user1, User This function will also be called and will set the attribute named name in the user1 object, whose value is Alex.
You can use the apply and call methods of function to specify the value of this when it is called. The first parameter of apply and call is the value of this to be specified. Because of their existence, we can create all kinds of useful functions.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn