728x90
11_This.html
<script>
//If the function is invoked using Function.call() or Function.apply(),
//this will be set to the first argument passed to .call()/.apply().
//If the first argument passed to .call()/.apply() is null or undefined,
//this will refer to the global object (which is the window object in web browsers).
//A function invoked using Function call()
var myObject ={
sayHello: function(){
console.log("Hi! My Name is "+this.myName);
},
myName: "Rebecca"
};
var secondObject = {
myName: "Colin"
};
myObject.sayHello(); // "Hi! My name is Rebecca"
myObejct.sayHello.call(secondObject); //"Hi! My name is Colin"
//call()은 메서드 호출, bind() 메서드를 새롭게 만들어 리턴
//A function created using Function.bind()
var myName = "the global obejct";
var sayHello = function(){
console.log("Hi! My name is " + this.myName);
};
var myObject ={
myName: "Rebecca"
};
var myObjectHello = sayHello.bind(myObject);
sayHello(); //"Hi! My name is the global object"
myObejctHello(); //"Hi! My name is Rebecca"
//A function being attached to an object at runtime.
var myName = "the global object";
var sayHello = function(){
console.log("Hi! My name is "+this.myName);
};
var myObject = {
myName: "Rebecca"
};
var secondObject ={
myName: "Colin"
};
myObject.sayHello = sayHello;
secondObject.sayHello = sayHello;
sayHello(); // "Hi My name is the global object"
myObject.sayHello(); //"Hi! My name is Colin"
var myNamespace = {
myObject: {
sayHello: function(){
console.log("Hi! My name is "+this.myName);
},
myName: "Rebecca"
}
};
var obj = myNamespace.myObject;
obj.sayHello(); // "Hi My name is Rebecca"
</script>
728x90
'JS > JavaScript' 카테고리의 다른 글
[JS] 13. Closure (0) | 2017.08.28 |
---|---|
[JS] 12. scope (0) | 2017.08.28 |
[JS] 10. TypeOf (0) | 2017.08.28 |
[JS] 09. Function (0) | 2017.08.28 |
[JS] 08. Object (0) | 2017.08.28 |
댓글