【发布时间】:2016-07-02 08:46:01
【问题描述】:
这种情况下的任何横向解决方案,当我需要知道我在哪个类而不使用绑定时。
function Customer() {}
Customer.prototype.say = function() {
console.log("I'm " + this.constructor.TYPE);
};
Customer.TYPE = 'customer';
function Product() {}
Product.prototype.say = function() {
console.log("I'm " + this.constructor.TYPE);
};
Product.TYPE = 'product';
var customer = new Customer();
var product = new Product();
//cleaner interface
Promise.resolve()
.then(customer.say) //I'm undefined
.then(product.say) //I'm undefined
//works but looking for a solution using cleaner interface like above
//any lateral thinking
Promise.resolve()
.then(customer.say.bind(customer)) //I'm customer
.then(product.say.bind(product)) //I'm product
我正在寻找基于非绑定的解决方案,任何基于横向思维的想法?
这是我正在开发的 SDK,因此希望提供更简洁的界面并供客户使用。
【问题讨论】:
-
您必须使用
bind或匿名函数,不确定您还期望什么... -
有什么方法可以在保持语法简洁的同时了解调用者的类型?
-
"在全局范围内调用" 不,调用时
this指的是全局对象(或严格模式下的undefined),与此无关范围。 -
使用函数而不是方法并显式传递对象,那么您将摆脱
bind和this -
@LUH3417 抱歉没找到你,怎么样?
标签: javascript static promise this