鉴于此课程; 我将如何迭代它包含的方法?
class Animal {
constructor(type){
this.animalType = type;
}
getAnimalType(){
console.log('this.animalType: ', this.animalType );
}
}
let cat = window.cat = new Animal('cat')
Run Code Online (Sandbox Code Playgroud)
我试过的是以下但没有成功:
for (var each in Object.getPrototypeOf(cat) ){
console.log(each);
}
Run Code Online (Sandbox Code Playgroud) 有没有办法确定JavaScript函数是否是绑定函数?
例:
var obj = {
x:1
};
function printX() {
document.write(this.x);
}
function takesACallback(cb) {
// how can one determine if this is a bounded function
// not just a function?
if (typeof cb === 'function') {
cb();
}
}
takesACallback(printX.bind(obj)); // 1
takesACallback(printX); // undefined
Run Code Online (Sandbox Code Playgroud)
也许这是一个重点.我不是在问为什么第二个调用打印未定义.
除了常规功能和内置功能之外,还有一种优雅的方式可以告诉Harmony的纤细箭头功能吗?
在和谐维基指出:
箭头函数就像内置函数一样缺乏.prototype和任何[[Construct]]内部方法.所以new(()=> {})抛出一个TypeError,否则箭头就像函数一样
这意味着,您可以测试箭头功能,如:
!(()=>{}).hasOwnProperty("prototype") // true
!(function(){}).hasOwnProperty("prototype") // false
Run Code Online (Sandbox Code Playgroud)
但是测试也将返回true
任何内置函数,例如setTimeout
或Math.min
.
如果您获得源代码并检查它是否可以在Firefox中运行"native code"
,但它看起来不太可靠也不可移植(其他浏览器实现,NodeJS/iojs):
setTimeout.toSource().indexOf("[native code]") > -1
Run Code Online (Sandbox Code Playgroud)
小的GitHub项目node-is-arrow-function依赖于函数源代码的RegExp检查,这不是那么整洁.
编辑:我尝试了一下JavaScript解析器橡子,看起来工作得很好 - 即使它太过分了.
acorn = require("./acorn");
function fn_sample(a,b){
c = (d,e) => d-e;
f = c(--a, b) * (b, a);
return f;
}
function test(fn){
fn = fn || fn_sample;
try {
acorn.parse("(" + fn.toString() + ")", {
ecmaVersion: 6,
onToken: function(token){ …
Run Code Online (Sandbox Code Playgroud) javascript function ecmascript-harmony ecmascript-6 arrow-functions