背景填充 显式函数绑定 this指向

HTML背景图填充完整

<style>

body{           

background-image: url(imgs/background7.jpg);

background-repeat: no-repeat;                     

background-size: 100% 100%;                     

background-attachment: fixed;                   

}

<style>


<center></center>灵活运用




<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<script>

function validateForm() {

    var x = document.forms["myForm"]["fname"].value;

    if (x == null || x == "") {

        alert("需要输入名字。");

        return false;

    }

}

</script>

</head>

<body>


<form name="myForm" action="demo_form.php"

onsubmit="return validateForm()" method="post">

名字: <input type="text" name="fname">

<input type="submit" value="提交">

</form>


</body>

</html>


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>菜鸟教程(runoob.com)</title>

</head>

<head>

<script>

function validateForm(){

var x=document.forms["myForm"]["email"].value;

var atpos=x.indexOf("@");

var dotpos=x.lastIndexOf(".");

if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length){

  alert("不是一个有效的 e-mail 地址");

    return false;

}

}

</script>

</head>

<body>

<form name="myForm" action="demo-form.php" onsubmit="return validateForm();" method="post">

Email: <input type="text" name="email">

<input type="submit" value="提交">

</form>

</body>

</html>

显式函数绑定

在 JavaScript 中函数也是对象,对象则有方法,apply 和 call 就是函数对象的方法。这两个方法异常强大,他们允许切换函数执行的上下文环境(context),即 this 绑定的对象。

在下面实例中,当我们使用 person2 作为参数来调用 person1.fullName 方法时, this 将指向 person2, 即便它是 person1 的方法:

实例

var person1 = {

  fullName: function() {

    return this.firstName + " " + this.lastName;

  }

}

var person2 = {

  firstName:"John",

  lastName: "Doe",

}

person1.fullName.call(person2);  // 返回 "John Doe"



this 的多种指向:

1、在对象方法中, this 指向调用它所在方法的对象。

2、单独使用 this,它指向全局(Global)对象。

3、函数使用中,this 指向函数的所属者。

4、严格模式下函数是没有绑定到 this 上,这时候 this 是 undefined。

5、在 HTML 事件句柄中,this 指向了接收事件的 HTML 元素。

6、apply 和 call 允许切换函数执行的上下文环境(context),即 this 绑定的对象,可以将 this 引用到任何对象。


简单理解,this指向的是该this所在的最里层的object对象。

1、函数不是object对象,所以没有写在object对象里的函数调用this会指向window

2、构造函数是object对象,所以在构造函数中调用this会指向该构造函数

3、html元素是object元素,所以在html元素中调用this会指向该元素

4、函数1 return 函数2,函数2 return this,该this会指向window

例:let obj = {

    fun1:function(){

        return function(){

            return this;

        }

    },

};

console.log(obj.fun1()()); //window

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容