为什么我不能访问对象内部的全局数组,而只能访问javascript原型中的全局数组



为什么我不能访问对象内部的b()函数中的全局array object?但我可以从原型中访问它。问题出在哪里?

let
root = window || this || globalThis;
/**
* 
* @run
*/
(function (global, factory) {
/**
* 
* @check
* if the factory is a function the run it
*/
if (typeof factory === 'function' && typeof global.__run === 'undefined')
global.__run = factory();
}(root, function () {
/**
* 
* @initialize
*/
let version = '2.0.0';
let arr = []; //global array....
let obj = {};
let isFunction = function (arg) {
return typeof arg === 'function';
}
let isString = function (arg) {
return typeof arg === 'string';
}
let isBoolean = function (arg) {
return typeof arg === 'boolean';
}
/***
* 
* @expression
*/
let
__run = function (selector) {
return new __run.init(selector);
}
/**
* 
* @extend
*/
let
init = __run.init = function (selector) {
arr = [selector];
return this;
};
__run.fn = init.prototype = __run.prototype;
__run.extend = function (arg) {
if (!arg instanceof Object)
return false;
for (key in arg) {
__run.fn[key] = function () {};
}
}
__run.fn.a = function () {
return arr //return array, success
}
/***
* 
* @DOM
* DOM manupulation.
*/
let
DOM = {
b: function () {
return arr //return undefined, error why?
}
}
__run.extend(DOM);
return __run;
}));
console.log(__run('h1').a()) //return array success
console.log(__run('h1').b()) //return undefined

您的问题在这里:

for (key in arg) {
__run.fn[key] = function(){}; // Here, you are basically assigning a new function
}

您必须将对象中的函数分配给__run.fn[key] = arg[key],它才能工作。arg[key]是可以访问arr的函数表达式。

b: function () 
{
return arr; 
}

在下面拉小提琴。

let
root = window || this || globalThis;
/**
* 
* @run
*/
(function (global, factory) {
/**
* 
* @check
* if the factory is a function the run it
*/
if (typeof factory === 'function' && typeof global.__run === 'undefined')
global.__run = factory();
}(root, function () {
/**
* 
* @initialize
*/
let version = '2.0.0';
let arr = []; //global array....
let obj = {};
let isFunction = function (arg) {
return typeof arg === 'function';
}
let isString = function (arg) {
return typeof arg === 'string';
}
let isBoolean = function (arg) {
return typeof arg === 'boolean';
}
/***
* 
* @expression
*/
let
__run = function (selector) {
return new __run.init(selector);
}
/**
* 
* @extend
*/
let
init = __run.init = function (selector) {
arr = [selector];
return this;
};
__run.fn = init.prototype = __run.prototype;
__run.extend = function (arg) {
if (!arg instanceof Object)
return false;
for (key in arg) {
__run.fn[key] = arg[key];
}
}
__run.fn.a = function () {
return arr //return array, success
}
/***
* 
* @DOM
* DOM manupulation.
*/
let DOM = {
b: function () 
{
return arr; //Yay, Now it works
}
}
__run.extend(DOM);
return __run;
}));
console.log(__run('h1').a()) //return array success
console.log(__run('h1').b()) //return undefined

extend函数中,将__run.fn中的新条目分配给一个空函数,函数的默认返回值为undefined。也就是说,这并不是说函数不能访问全局变量,而是函数为空并且不返回任何内容。更改

__run.fn[key] = function () {};

__run.fn[key] = arg[key];

在CCD_ 11中,它应该工作。

最新更新