Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // this
- var a = {
- name: 'Вася',
- getName: function () {
- return this.name;
- },
- getContext: function() {
- return this;
- }
- }
- a.name; // ???
- a.getName(); // ???
- a.getContext(); // ???
- // или можем через a.name, но это опасно
- var a = {
- name: 'Вася',
- getName: function () {
- return a.name;
- },
- getContext: function() {
- return this;
- }
- };
- var admin = a;
- a = null;
- admin.sayHi(); // error
- // Использование this гарантирует, что функция работает именно с тем объектом, в контексте которого вызвана.
- // ---------------------------------------
- // this examples
- // ---------------------------------------
- // 1. Простой вызов function
- function f() {
- console.log(this === window); // true
- }
- f();
- // 2. Constructor
- function f() {
- this.x = 5;
- console.log(this === window); // false
- }
- var o = new f();
- console.log(o.x === 5); // true
- // 3. Метод obj
- var o = {
- f: function() {
- return this;
- }
- }
- console.log(o.f() === o); // true
- // 4. Методы apply, call
- function f() {
- console.log(this.toString()); // 123
- }
- f.call(123); // this внутри функции f будет ссылаться на объект Number со значением 123
- // 5. bind
- function f() {
- console.log(this.x);
- }
- var bound = f.bind({x: 3}); // bound - новая функция - "обертка", у которой this ссылается на объект {x:3}
- bound();// Выведет 3
- // ---------------------------------------
- // Tasks
- // ---------------------------------------
- // 1
- var f = function() {
- this.x = 5;
- (function() {
- this.x = 3;
- })();
- console.log(this.x); //
- };
- new f();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement