我想获取父类名(import Foundation
import UIKit
import Darwin
class View3on3 : UIViewController, UITextFieldDelegate {
@IBOutlet weak var APTeams: UITextField!
@IBOutlet weak var APRounds: UITextField!
@IBOutlet weak var APBreakers: UITextField!
@IBOutlet weak var ToAPBreak: UIButton!
override func viewDidLoad()
{
super.viewDidLoad()
initializeTextFields()
APTeams.delegate = self
APRounds.delegate = self
APBreakers.delegate = self
ToAPBreak.backgroundColor = UIColor.clearColor()
ToAPBreak.layer.cornerRadius = 11
ToAPBreak.layer.borderWidth = 1
ToAPBreak.layer.borderColor = self.view.tintColor.CGColor
}
func initializeTextFields()
{
APTeams.keyboardType = UIKeyboardType.NumberPad
APRounds.keyboardType = UIKeyboardType.NumberPad
APBreakers.keyboardType = UIKeyboardType.NumberPad
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if (textField == APTeams){
APRounds.becomeFirstResponder()
} else if (textField == APRounds){
APBreakers.becomeFirstResponder()
} else if (textField == APBreakers){
APBreakers.resignFirstResponder()
} else {
//etc//
}
return true
}
),但我只能使用此代码(Parent
)检索子类名...
Child

有可能吗?
谢谢!
答案 0 :(得分:33)
ES6类相互继承。因此,当Child
引用Object.getPrototypeOf(instance.constructor)
时,您可以使用Parent
获取Object.getPrototypeOf(instance.constructor).name == "Parent";
,然后访问.name
:
{{1}}
当然,完整的ES6合规性和非缩小代码是必不可少的。你不应该依赖代码中的函数名。
答案 1 :(得分:4)
这是有趣的事情:
class J {}
class K extends J {}
class L extends K {}
function getBaseClass(targetClass){
if(targetClass instanceof Function){
let baseClass = targetClass;
while (baseClass){
const newBaseClass = Object.getPrototypeOf(baseClass);
if(newBaseClass && newBaseClass !== Object && newBaseClass.name){
baseClass = newBaseClass;
}else{
break;
}
}
return baseClass;
}
}
console.log(getBaseClass(L)); // Will return J.
答案 2 :(得分:1)
你可以在技术上做到
// instanceProto === Child.prototype
var instanceProto = Object.getPrototypeOf(instance);
// parentProto === Parent.prototype
var parentProto = Object.getPrototypeOf(instanceProto);
console.log(parentProto.constructor.name);
请记住,这些名称可能都会被缩小器破坏。
答案 3 :(得分:0)
答案 4 :(得分:0)
另一种简单的解决方案:
class Foo {}
class Bar extends Foo{}
Object.getPrototypeOf(Bar) === Foo // true
Bar.__proto__ === Foo // true
console.log(Bar.__proto__.name) // Foo