分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

06慕课网《进击Node.js基础(一)》作用域和上下文

发布时间:2023-09-06 01:56责任编辑:顾先生关键词:jsNode作用域

作用域

调用函数访问变量的能力

//全局变量var globalVariable = ‘This is global variable‘//全局函数function globalFunction(){ ???//局部变量 ???var localVariable = ?‘This is local variable‘ ???console.log(‘visit gloabl/local variable‘) ???console.log(globalVariable) ???console.log(localVariable) ???globalVariable = ‘this is change variable‘ ???console.log(globalVariable) ???//局部函数 ???function loaclFunction(){ ???????//局部变量 ???????var innerLocalVariable = ‘this is inner local variable‘ ???????console.log(‘visit gloabl/local/innerLocal variable‘) ???????console.log(globalVariable) ???????console.log(localVariable) ???????console.log(innerLocalVariable) ???} ???//作用域内可访问局部函数 ???loaclFunction()}//在全局不能访问局部变量和函数globalFunction()

上下文

和this关键字有关,是调用当前可执行代码的对象的引用

this指向函数拥有者,只能在函数中使用

this指向构造函数
var pet = { ???words:‘..‘, ???speak:function(){ ???????console.log(this.words) ???????console.log(this==pet) ???}}pet.speak()
this指向全局对象
function pet(words){ ???this.words = words ???console.log(this.words) ???console.log(this==global)}//this指向了全局global对象pet(‘..‘)
this指向实例对象
function Pet(words){ ???this.words = words ???this.speak = function(){ ???????console.log(this.words) ???????console.log(this) ???}}var cat = new Pet(‘Miao‘)cat.speak();

使用call和apply改变上下文引用对象

this指向引用方法的对象
var pet = { ???words:‘..‘, ???speak:function(say){ ???????console.log(say + ‘ ‘ + this.words) ???}}pet.speak(‘haha‘)
使用call-apply
var pet = { ???words:‘..‘, ???speak:function(say,free){ ???????console.log(say + ‘ ‘ + free+ ‘ ‘+ this.words) ???}}var dog={ ???words:‘wawa‘}pet.speak.call(dog,‘haha‘,‘lala‘)pet.speak.apply(dog,[‘haha‘,‘lala‘])
使用call和apply方便实现继承
function Pet(words){ ???this.words = words ???this.speak = function(){ ???????console.log(this.words) ???}}//Dog继承Pet,拥有了Pet的speak方法function Dog(words){ ???Pet.call(this,words)}var dog = new Dog(‘wawa‘)dog.speak()

06慕课网《进击Node.js基础(一)》作用域和上下文

原文地址:https://www.cnblogs.com/-beauTiFul/p/9095696.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved