this

The this keyword refers to the current instance of a class within its methods. It provides access to instance variables, methods, and properties from within the class context.

Basic This Usage

Access instance properties and methods:
sanctuary User {
    soul __genesis__(name, email) {
        this.name = name
        this.email = email
        this.loginCount = 0
    }
    
    soul getName() {
        return this.name
    }
    
    soul getEmail() {
        return this.email
    }
    
    soul login() {
        this.loginCount = this.loginCount + 1
        println("User " + this.name + " logged in")
    }
}

user = User("Alice", "alice@example.com")
println(user.getName())  // "Alice"
user.login()  // "User Alice logged in"

This in Property Access

Use this to access and modify instance properties:
sanctuary BankAccount {
    soul __genesis__(accountNumber, initialBalance) {
        this.accountNumber = accountNumber
        this.balance = initialBalance
        this.isActive = true
    }
    
    soul deposit(amount) {
        if (amount > 0) {
            this.balance = this.balance + amount
            println("Deposited $" + amount + ". New balance: $" + this.balance)
        }
    }
    
    soul withdraw(amount) {
        if (amount > 0 && amount <= this.balance) {
            this.balance = this.balance - amount
            println("Withdrew $" + amount + ". New balance: $" + this.balance)
        } else {
            println("Insufficient funds")
        }
    }
    
    soul getBalance() {
        return this.balance
    }
    
    soul getAccountInfo() {
        return {
            "number": this.accountNumber,
            "balance": this.balance,
            "active": this.isActive
        }
    }
}

account = BankAccount("123456", 1000)
account.deposit(500)
account.withdraw(200)
println(account.getBalance())  // 1300

This in Method Chaining

Enable method chaining by returning this:
sanctuary StringBuilder {
    soul __genesis__() {
        this.content = ""
    }
    
    soul append(text) {
        this.content = this.content + text
        return this  // Enable chaining
    }
    
    soul appendLine(text) {
        this.content = this.content + text + "\n"
        return this  // Enable chaining
    }
    
    soul clear() {
        this.content = ""
        return this  // Enable chaining
    }
    
    soul toString() {
        return this.content
    }
}

result = StringBuilder()
    .append("Hello ")
    .append("World")
    .appendLine("!")
    .append("How are you?")
    .toString()

println(result)  // "Hello World!\nHow are you?"

This with Private Methods

Use this to call private methods:
sanctuary Calculator {
    soul __genesis__() {
        this.history = []
    }
    
    soul add(a, b) {
        result = a + b
        this._logOperation("add", a, b, result)
        return result
    }
    
    soul subtract(a, b) {
        result = a - b
        this._logOperation("subtract", a, b, result)
        return result
    }
    
    soul multiply(a, b) {
        result = a * b
        this._logOperation("multiply", a, b, result)
        return result
    }
    
    // Private method (convention: starts with _)
    soul _logOperation(operation, a, b, result) {
        entry = {
            "operation": operation,
            "operands": [a, b],
            "result": result,
            "timestamp": getCurrentTime()
        }
        this.history.push(entry)
    }
    
    soul getHistory() {
        return this.history
    }
}

calc = Calculator()
calc.add(5, 3)
calc.multiply(4, 2)
println(calc.getHistory())

This in Static vs Instance Methods

Distinguish between static and instance method contexts:
sanctuary MathUtils {
    soul __genesis__() {
        this.precision = 2
    }
    
    // Instance method - has access to `this`
    soul formatNumber(number) {
        return number.toFixed(this.precision)
    }
    
    // Static method - no access to `this`
    static soul add(a, b) {
        return a + b
    }
    
    static soul multiply(a, b) {
        return a * b
    }
    
    // Instance method using static method
    soul calculate(a, b, operation) {
        result = null
        
        switch (operation) {
            case "add":
                result = MathUtils.add(a, b)
                break
            case "multiply":
                result = MathUtils.multiply(a, b)
                break
            default:
                return "Unknown operation"
        }
        
        return this.formatNumber(result)
    }
}

// Static method call - no instance needed
sum = MathUtils.add(5, 3)  // 8

// Instance method call - needs instance
utils = MathUtils()
formattedSum = utils.calculate(5, 3, "add")  // "8.00"

This with Inheritance

Use this in inheritance hierarchies:
sanctuary Animal {
    soul __genesis__(name, species) {
        this.name = name
        this.species = species
    }
    
    soul speak() {
        println(this.name + " makes a sound")
    }
    
    soul getInfo() {
        return this.name + " is a " + this.species
    }
}

sanctuary Dog extends Animal {
    soul __genesis__(name, breed) {
        super(name, "Dog")  // Call parent constructor
        this.breed = breed
    }
    
    soul speak() {
        println(this.name + " barks")
    }
    
    soul getBreed() {
        return this.breed
    }
    
    soul getFullInfo() {
        return this.getInfo() + " (" + this.breed + ")"
    }
}

dog = Dog("Buddy", "Golden Retriever")
dog.speak()  // "Buddy barks"
println(dog.getFullInfo())  // "Buddy is a Dog (Golden Retriever)"

This in Event Handlers

Use this in event handling contexts:
sanctuary Button {
    soul __genesis__(label) {
        this.label = label
        this.clickCount = 0
        this.isEnabled = true
    }
    
    soul onClick() {
        if (this.isEnabled) {
            this.clickCount = this.clickCount + 1
            println("Button '" + this.label + "' clicked " + this.clickCount + " times")
            this._handleClick()
        }
    }
    
    soul _handleClick() {
        // Custom click handling logic
        if (this.clickCount == 5) {
            println("Button '" + this.label + "' has been clicked 5 times!")
        }
    }
    
    soul disable() {
        this.isEnabled = false
        println("Button '" + this.label + "' disabled")
    }
    
    soul enable() {
        this.isEnabled = true
        println("Button '" + this.label + "' enabled")
    }
}

button = Button("Submit")
button.onClick()  // "Button 'Submit' clicked 1 times"
button.onClick()  // "Button 'Submit' clicked 2 times"
button.disable()
button.onClick()  // No output - button is disabled

This with Getters and Setters

Use this with property accessors:
sanctuary Temperature {
    soul __genesis__(celsius) {
        this._celsius = celsius
    }
    
    soul getCelsius() {
        return this._celsius
    }
    
    soul setCelsius(celsius) {
        this._celsius = celsius
    }
    
    soul getFahrenheit() {
        return (this._celsius * 9/5) + 32
    }
    
    soul setFahrenheit(fahrenheit) {
        this._celsius = (fahrenheit - 32) * 5/9
    }
    
    soul getKelvin() {
        return this._celsius + 273.15
    }
    
    soul setKelvin(kelvin) {
        this._celsius = kelvin - 273.15
    }
    
    soul toString() {
        return this._celsius + "°C (" + this.getFahrenheit() + "°F)"
    }
}

temp = Temperature(25)
println(temp.toString())  // "25°C (77°F)"
temp.setFahrenheit(100)
println(temp.getCelsius())  // 37.777...

This in Validation Methods

Use this for object validation:
sanctuary User {
    soul __genesis__(username, email, age) {
        this.username = username
        this.email = email
        this.age = age
    }
    
    soul isValid() {
        return this._validateUsername() && 
               this._validateEmail() && 
               this._validateAge()
    }
    
    soul _validateUsername() {
        return this.username != null && 
               this.username.length() >= 3 && 
               this.username.length() <= 20
    }
    
    soul _validateEmail() {
        return this.email != null && 
               this.email.contains("@") && 
               this.email.contains(".")
    }
    
    soul _validateAge() {
        return this.age != null && 
               this.age >= 13 && 
               this.age <= 120
    }
    
    soul getValidationErrors() {
        errors = []
        
        if (!this._validateUsername()) {
            errors.push("Username must be 3-20 characters")
        }
        
        if (!this._validateEmail()) {
            errors.push("Invalid email format")
        }
        
        if (!this._validateAge()) {
            errors.push("Age must be between 13 and 120")
        }
        
        return errors
    }
}

user = User("ab", "invalid-email", 5)
if (!user.isValid()) {
    errors = user.getValidationErrors()
    for (error in errors) {
        println("Error: " + error)
    }
}

This with Callback Functions

Use this in callback contexts:
sanctuary Timer {
    soul __genesis__(duration) {
        this.duration = duration
        this.isRunning = false
        this.timeElapsed = 0
    }
    
    soul start() {
        if (!this.isRunning) {
            this.isRunning = true
            this.timeElapsed = 0
            println("Timer started for " + this.duration + " seconds")
            this._scheduleCallback()
        }
    }
    
    soul _scheduleCallback() {
        // Simulated callback that maintains `this` context
        callback = soul() {
            this.timeElapsed = this.timeElapsed + 1
            println("Time elapsed: " + this.timeElapsed + " seconds")
            
            if (this.timeElapsed >= this.duration) {
                this._onComplete()
            } else {
                this._scheduleCallback()
            }
        }
        
        // In real implementation, this would use actual timer
        callback()
    }
    
    soul _onComplete() {
        this.isRunning = false
        println("Timer completed after " + this.duration + " seconds")
    }
    
    soul stop() {
        if (this.isRunning) {
            this.isRunning = false
            println("Timer stopped at " + this.timeElapsed + " seconds")
        }
    }
}

timer = Timer(3)
timer.start()

This with Fluent Interface

Create fluent interfaces using this:
sanctuary QueryBuilder {
    soul __genesis__() {
        this.query = ""
        this.conditions = []
        this.orderBy = ""
        this.limitValue = null
    }
    
    soul select(fields) {
        this.query = "SELECT " + fields
        return this
    }
    
    soul from(table) {
        this.query = this.query + " FROM " + table
        return this
    }
    
    soul where(condition) {
        this.conditions.push(condition)
        return this
    }
    
    soul orderBy(field) {
        this.orderBy = " ORDER BY " + field
        return this
    }
    
    soul limit(count) {
        this.limitValue = count
        return this
    }
    
    soul build() {
        finalQuery = this.query
        
        if (this.conditions.length() > 0) {
            finalQuery = finalQuery + " WHERE " + this.conditions.join(" AND ")
        }
        
        if (this.orderBy != "") {
            finalQuery = finalQuery + this.orderBy
        }
        
        if (this.limitValue != null) {
            finalQuery = finalQuery + " LIMIT " + this.limitValue
        }
        
        return finalQuery
    }
}

query = QueryBuilder()
    .select("name, email")
    .from("users")
    .where("age > 18")
    .where("active = true")
    .orderBy("name")
    .limit(10)
    .build()

println(query)  // "SELECT name, email FROM users WHERE age > 18 AND active = true ORDER BY name LIMIT 10"

Best Practices

  1. Always use this: Explicitly use this for instance members
  2. Return this for chaining: Enable method chaining by returning this
  3. Validate this context: Ensure this is available in the current context
  4. Use this consistently: Maintain consistent usage throughout class methods
  5. Document this usage: Make it clear when methods modify this
sanctuary Configuration {
    soul __genesis__() {
        this.settings = {}
        this.isModified = false
    }
    
    // Good - explicit this usage
    soul set(key, value) {
        this.settings[key] = value
        this.isModified = true
        return this  // Enable chaining
    }
    
    soul get(key) {
        return this.settings[key]
    }
    
    soul has(key) {
        return key in this.settings
    }
    
    soul reset() {
        this.settings = {}
        this.isModified = false
        return this
    }
    
    soul save() {
        if (this.isModified) {
            println("Saving configuration...")
            this.isModified = false
        }
        return this
    }
}

config = Configuration()
    .set("theme", "dark")
    .set("language", "en")
    .save()

println(config.get("theme"))  // "dark"
The this keyword is essential for object-oriented programming in Soul, providing access to instance context and enabling clean, readable class implementations.