这在call()中是指什么

时间:2018-04-08 12:47:10

标签: javascript

function hello (val){

  console.log(this, val);
}

console.log(hello('jumbo'))

let obj = {
  'name':'Pranjal'
};

var h = new hello.call(this, obj)

2 个答案:

答案 0 :(得分:0)

<!DOCTYPE html>
<html>
<title>Web Page Design</title>
<head>
<script>
function hello (val){
  document.write('<br>'+this, val);
  //Focus here
  document.write('<br>Here'+this+'is referred to the function which is part of window object.')
  //In Object orienrted technology 'this' is used to refer the object/function under which//we are working. As here if we say this then it refers to the function hello which//is part of window object.
}
//See this is part of window object.
window.hello('jumbo');//Works
//Same as
hello('jumbo');//Works as well
//So this prints twice.



</script>
</head>
<body>
</body>
</html>

这里'this'是一个关键字,用于指代我们运作的确切事物。在这里,这是指函数hello(),因此document.write()或console.log()将显示[对象窗口]。 请在此处参考面向对象的编程概念: https://www.geeksforgeeks.org/this-pointer-in-c/

答案 1 :(得分:0)

call()可用于调用它所渴望的任何函数,即使它属于某个其他对象也是如此。 这里hello.call(this)将发送全局对象call()。检查代码运行它并阅读注释。

&#13;
&#13;
<!DOCTYPE html>
<html>
<title>Web Page Design</title>
<head>
<script>
//Meaning of call
var person = {
    firstName:"John",
    lastName: "Doe",
    fullName: function() {
        document.write(this.firstName + " " + this.lastName+'<br>');
    }
}
var myObject = {
    firstName:"Mary",
    lastName: "Doe",
}
//can use function of other objects.
person.fullName.call(myObject);//refers to object i.e there in call();

//Solution
function hello (val){
  document.write('<br>'+val+'<br>');
  document.write('Here'+this+'is referred to the function which is part of window object.<br><br>')
}
//Watch what it prints at 'this';
hello.call('||||||other thing||||||||');//other things is printed.
hello(',,,,,Some other thing,,,,,,');//but here 'this' prints window object.
hello.call('@@@@Hmm@@@');//Again prints which is there in call();
//So we can conclude
hello.call(this);//Here the window object that is passed is call() not Hello().


</script>
</head>
<body>
</body>
</html>
&#13;
&#13;
&#13;