JS如何调用函数内部变量?

JavaScript013

JS如何调用函数内部变量?,第1张

JS调用函数内部变量有以下两种方法:

1、添加return返回值

var a = 5

function xxx(){

    var a = 10

    return a

}

var b = xxx()//这里的b就是10

2、闭包

var a = 5

function xxx(){

    var a = 0

    var ten = function(){

        a = 10

        return a

    }

    return ten

}

var b = xxx()

b()

ts 调用 js

步骤

找到 js 调用 js 的方法。

增加方法调用的声明。 请参考 如何生成 .d.ts 。

示例

js 内的方法

function callJsFunc(msg) {    console.log("msg from egret : " + msg)}

ts 内声明

declare function callJsFunc(msg:string)//可以放在 ts 文件内(建议在顶部或者底部,中间的没试过)或者单独放到一个 .d.ts 文件中,请不要放在其他类型的文件内。msg 类型根据函数体判断。

ts 内调用

callJsFunc("hello js")

输出

msg from egret : hello js

总结:在 js 调用 js 的基础上增加声明。其他的比如变量等,也是按上面步骤来实现。

js 调用 ts

js 调用 ts 其实就是 ts 调用 ts,由于 ts 调用 ts 可能会有同模块下的省略写法,因此只要使用不同模块下的调用来写即可。

步骤

找到非同一模块下 ts 的调用(比如 example.A.CallEgretFunc("hello"))。

完全按上面调用的方式来写 (比如上面的 example.A.CallEgretFunc("hello"))。

示例

ts 内的方法

module exampleA {    export class A {        public callEgretMethod(msg:string):void {            console.log("method msg from js : " + msg)       }        public static CallEgretFunc(msg:string):void {            console.log("static msg from js : " + msg)       }    }}

非同一模块下 ts 调用

module exampleB {    export function b() {        //调用方法        var a:exampleA.A = new exampleA.A()       a.callEgretMethod("method")       //调用静态函数        exampleA.A.CallEgretFunc("function")   }}

js 内调用

var a = new exampleA.A()//去掉 a 的类型a.callEgretMethod("method")exampleA.A.CallEgretFunc("function")

输出

method msg from js : methodstatic msg from js : function

JS函数的定义与调用方法

JS函数调用的四种方法:方法调用模式,函数调用模式,构造器调用模式,apply,call调用模式

1.方法调用模式:

先定义一个对象,然后在对象的属性中定义方法,通过myobject.property来执行方法,this即指当前的myobject

对象。

var blogInfo={

blogId:123,

blogName:"werwr",

showBlog:function(){alert(this.blogId)}

}

blogInfo.showBlog()

2.函数调用模式

定义一个函数,设置一个变量名保存函数,这时this指向到window对象。

var myfunc = function(a,b){

return a+b

}

alert(myfunc(3,4))

3.构造器调用模式

定义一个函数对象,在对象中定义属性,在其原型对象中定义方法。在使用prototype的方法时,必须实例化该对象才能调用其方法。

var myfunc = function(a){

this.a = a

}

myfunc.prototype = {

show:function(){alert(this.a)}

}

var newfunc = new myfunc("123123123")

newfunc.show()

4.apply,call调用模式

var myobject={}

var sum = function(a,b){

return a+b

}

var sum2 = sum.call(myobject,10,30)//var sum2 = sum.apply(myobject,[10,30])

alert(sum2)