美文网首页
self.属性/方法 调用

self.属性/方法 调用

作者: chenhh6701 | 来源:发表于2018-04-12 11:02 被阅读5次

    self一般是指当前执行或所有对象

    self.属性/方法 调用优先级: (先private -> public)
    1.当代码所在类的 private属性/方法
    2.子类->超类

    在继承环境中:
    superClass中调用:
    self.属性/方法: 先调用代码当前类的私有

    Bug:
    如果superClass中有private 属性/方法 和subClass 属性/方法 同名,那就调用superClass自己的private 属性/方法

    解决:
    private 属性/方法 添加前缀 : 如 p_ 属性/方法

    import Foundation
    
    print("Hello, World!")
    
    class Chang {
        var height:Double
        private var width:Double {
            willSet{
                print("super width willSet")
            }
        }
        init(height:Double,width:Double = 3) {
           
            self.width = width
            self.height = height
        }
        
        func argumentFunc(_ test:Double){
            self.width = test
            
            self.testFunc()
        }
      
        
        private func testFunc(){
            print("super testFunc")
        }
    }
    
    
    class Zheng:Chang{
        var width: Double = 15 {
            willSet{
                print("self width willSet")
            }
        }
        override func argumentFunc(_ test:Double){
            super.argumentFunc(test)
        }
        
        func testFunc(){
            print("super testFunc")
        }
    }
    

    输出:

    var test2 = Zheng(height:6,width:4)
    print(test2.width)
    test2.width = 5
    print(test2.width)
    test2.argumentFunc(6)
    print(test2.width)
    

    相关文章

      网友评论

          本文标题:self.属性/方法 调用

          本文链接:https://www.haomeiwen.com/subject/iulxkftx.html